Some angularJS usage and angularJS usage

Source: Internet
Author: User

Some angularJS usage and angularJS usage

AngularJS

Event command:

ng-click/dblclickng-mousedown/upng-mouseenter/leaveng-mousemove/over/outng-keydown/up/pressng-focus/blurng-submit

Like ng-click, events are bound to the dom.

Note that when using event objects, You need to input $ event in ng-click and other commands, such:

<button ng-click="clickFn($event)" class="btn btn-danger">aa</button>

Form instruction

ng-change

It will be useful when the value changes

Some labels with value values can be used only for ng-model.

Ng-model must be used together

Data verification is supported.

Whether the ng-disabled control element is available ng-readonlyng-checked

Control whether checkbox is selected

You can only set this parameter to control whether or not to select data.

Set ng-model to control data.

Difference between disabled and readonly

All form elements can be disabled by setting the disabled or readonly attribute. After the disabled attribute is set, users cannot use it and the form does not submit this field. readonly

Only disabled by the user, that is, the user is not allowed to operate, but the form will still be submitted

Small countdown flash sale case

$ Interval is equivalent to setInterval, and dirty data can be checked automatically.

If it is cleared, assign a value and then $ interval. cancel (timer)

Ng-show is displayed as true. False hide

Hide ng-hide with true. False

Ng-if is the same as ng-show, but if it is not displayed, the node is not in the dom document.

var app = angular.module("myapp",[])app.controller("myController",function ($scope,$interval) {$scope.num=1$scope.canBuy = false$scope.time = 5  var timer = $interval(function () {   $scope.time--;   if($scope.time<=0){    $scope.canBuy=true    $interval.cancel(timer)        }  },1000) })

Ng-bind-related

Ng-bind has a problem. After adding it, you cannot add other things behind the data variable. This label can only display this data, and others will not work. For example

{Name }}--- 111 using ng-bind-template = "{name} --- 111"

The tag cannot be resolved due to another problem.

No, use ng-bind-html.

ng-bind-html="

This is not the case. This is the first version of 1.3. when I switched from 1.3 to, I used a plug-in (module) to streamline angular. js)

You have to add "ngSanitize" to angular. module"

Then you need to put the label to be displayed on a variable, and then set it to ng-bind-html

$scope.text= "

This command does not parse the expression.

Ng-include

You can introduce an html code snippet, define variables, and write expressions in the code snippet.

$scope.text='html/a.html';ng-include='text'

Note that the internal request is ajax, so the server environment is required.

ng-model-options='{updateOn:'blur'}'

During the data binding process, nodes are always operated internally and the performance is poor. You can configure this to update the data displayed in the view at a certain time.

AngularJS

ng-controller

You can use object-oriented thinking to write controller

<div ng-controller="myController as myFun"> {{name}}<br>{{myFun.age}}<br>{{myFun.sex}}</div>myapp.controller("myController",["$scope",myFun])function myFun($scope){ $scope.name='allen'; this.sex='male'}myFun.prototype.age="18"

In addition, services have already been mentioned a lot.

In angularJS, services are used to pass certain functions

$ Http service

Data Interaction

$http({ url:"http://datainfo.duapp.com/shopdata/getclass.php", method:"get", params:{}}).success(function(data){ $scope.dataList=data;}).error(function(error){ console.log(error)})

Method indicates the transfer method get, post

Url Data Interface

The data submitted by params is equivalent to the data :{} in $. ajax :{}

Successful success callback

Error callback

Let's talk about the JSONP technology.

JSONP is a common method to solve cross-domain problems.

Cross-origin problem: Because the browser has a same-origin policy, cross-origin problems may occur when data is exchanged between different domains.

Same-origin policy: Data interaction can only be performed under the same protocol, domain name, and Port

JSONP principle: the src attribute of the script tag (the callback function is used to receive data) is not affected by the same-origin policy. You can request data from different domains and set a callback letter.

Number to receive data

JSONP is a cross-origin method that combines the frontend and backend. Because the frontend requests to data need to be used in the callback function, the backend must put the data back into the callback function.

Does JSONP belong to AJAX? Ajax is a technology that uses xmlhttprequest objects for asynchronous data interaction. jsonp is obtained by using the scriptsrc attribute, not ajax.

What are the disadvantages of JSONP? What should I pay attention to when using JSONP?

You cannot post cross-origin processing. Note that the script tag and callback function should be dynamically created for each request and destroyed after the data is obtained.

If the method is jsonp, jsonp can be used for cross-origin requests, but note that the callback value after the url is JSON_CALLBACK.

Baidu search example

Here the reference is angular-sanitize.js

var app = angular.module("myapp",['ngSanitize'])app.controller("myController",function ($scope,$http) {  $http({   url:"http://datainfo.duapp.com/shopdata/getclass.php",   method:"post",   params:{a:1}  }).success(function (results) {   $scope.dataList = results  }).error(function (error) {   console.log(error)  }) }) app.controller("yourController",function ($scope,$http) {  $scope.search = function () {   $http({    url:"https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su",    method:"jsonp",    params:{     wd:$scope.wd,     cb:'JSON_CALLBACK'    }   }).success(function (results) {    $scope.dataList = results.s   })  } })

$ Location service

Console. log ($ location. absUrl () // The absolute output address is console. log ($ location. host () // output domain name console. log ($ location. port () // output port console. log ($ location. protocol () // protocol $ location. path ("aaa") // control the console on the routing switch page. log ($ location. path () // #/aaa

$ Log Service

Multiple console Output Modes

$log.info("info");$log.warn("warn");$log.error("error");$log.log("log");

AngularJs configuration for Service Providers

For example

myapp.config(["$interpolateProvider",function($interpolateProvider){ $interpolateProvider.startSymbol("!!"); $interpolateProvider.endSymbol("!!");}])

Angular does not know {} anymore. It starts to become !!!!

Custom Service

1. factory

myapp.factory('serviceName',function(){  return ....})

Return string, array, function, and object (most used, most logical)

The introduction method is exactly the same as the $ service added in front of angualr. The usage method depends on what is returned, and the Custom Service name should not be added.

Eq: a service that returns a random number between two numbers.

myapp.factory("myService",function(){ return {  getRandom:function(a,b){   return Math.random()*(b-a)+a;  } }})

Custom services can be injected with other services.

myapp.factory('myHttpService',['$http',function($http){   return {     $http({       url:......     })           }}])

Eq: The next custom http service

myapp.factory("myHttpService",["$http",function($http){  return {    http:function(url,sfn,efn){      $http({        url:url,        method:"get"      }).success(sfn).error(efn)    }  }}])myHttpService.http("http://datainfo.duapp.com/shopdata/getclass.php",function(data){  console.log(data)},function(data){  console.log(data)})

2. provider

You can customize a service provider to define a service. The writing method is different. The functional items of the service need to be nested with a layer of response.

Myapp. provider ('myhttpservice', ['$ http', function ($ http) {return {$ get: function () {return :{// here is the output }}])

The service supplier is returned from the outside. The $ get method of the supplier returns the portion for our use. You can change some parameters of the supplier to control the service function,

Eq: returns a random number in the range, but controls whether the service returns an integer or a decimal number by configuring a supplier value.

myapp.provider("myService",function(){  return {    isInt:true,    $get:function(){      var that=this;      return {        getRandom:function(a,b){          var num=Math.random()*(b-a+1)+a;          if(that.isInt){            return Math.floor(num);          }else{            return(num)          }        }      }    }  }})myapp.config(["myServiceProvider",function(myServiceProvider){  myServiceProvider.isInt=false;}])

The Service created in this way can be configured by the supplier.

3. service

In this way, only objects can be created.
The simplest creation method, with built-in return, supports object-oriented writing

myapp.service("myService",function(){    this.getRandom=function(a,b){      return Math.random()*(b-a)+a;    }})myapp.service("myService",aaa)function aaa(){  this.getRandom=function(a,b){    return Math.random()*(b-a)+a;  }}

Data sharing between multiple controllers

There are three methods to achieve data sharing among multiple controllers,

The first one is relatively simple. You can access all the data in the parent scope.

The second is to find the sibling scope in the Controller through $ prevSibling and then use the data. Note that if it is the initial data type, data cannot be bound in two-way.

The third is to define services and make the data to be shared into services.

<body>  <div class="container">    <div ng-controller="firstController">      <input type="text" class="form-control" ng-model="name">      <input type="text" class="form-control" ng-model="data.name">      <input type="text" class="form-control" ng-model="Data.name">      <p>        first-name:{{name}}<br>        first-data-name:{{data.name}}<br>        first-Data-name:{{Data.name}}      </p>    </div>    <div ng-controller="secondController">      <p>        second-name:{{name}}<br>        second-data-name:{{data.name}}<br>        second-Data-name:{{Data.name}}      </p>    </div>  </div></body><script src="../Base/angular.min.js"></script><script>  var app=angular.module("myapp",[]);  app.factory("Data",function () {    return {      name:'lily'    }  })  app.controller("firstController",function ($scope,Data) {    $scope.name="allen";    $scope.data={      name:'tom'    }    $scope.Data=Data;  })  app.controller("secondController",function ($scope,Data) {    $scope.name=$scope.$$prevSibling.name;    $scope.data=$scope.$$prevSibling.data;    $scope.Data=Data;  })</script>

Custom Module

All modules have services. ng-app is the module reason for service of $ scope or something,

We can also write a module, and then write services in it.

In this way, you can write some services in a custom module to implement repeated calls.

For example, write the example of a random number in a custom module.

var myModule=angular.module("myModule",[]);myModule.service("myService",function(){  this.ran=function(a,b){   return Math.random()*(a+b)-a;  }})var myapp=angular.module("myapp",["myModule"]);myapp.controller("myController",["$scope","$log","myService",function($scope,$log,myService){ $log.log(myService.ran(5,10))}])

In fact, angualr. sanitize. js is a custom module.

Summary

The above is a small series of angularJS usage, I hope to help you, if you have any questions, please leave a message, the small series will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.