AngulaJS combat summary, take you into the AngularJS world (Continued)

Hybrid App using AngularJS development has been carried out more than a year, and make a summary here.

 

A, AngularJS initialization process load

 

1, the browser loads HTML, and then parse it into a DOM.
2, the browser loads angular.js script.
3, AngularJS until DOMContentLoaded event is triggered.
4, AngularJS Looking ng-app directive, which indicates the boundary of the application.
5, using ng-app module configuration specified in the injector ($ injector).
6, injectors ($ injector) is used to create the "Compile service ($ compile service)" and "root scope ($ rootScope)" is.
7. Build Service ($ compile service) DOM is used to compile and link it to the root scope ($ rootScope) of.
8, ng-init command to "World" in the name assigned to the scope of this variable.
9, by replacing {{name}}, the whole expression becomes a "Hello World".

 

二、AngularJS Provider/Service/Factory

 

1. What is the provider?

The service provider may provide a common application form can be a constant, it can be an object.

For example, we injected come in the controller $ http, $ scope can be considered provider.

app.controller('MainCtrl', function ($scope, $http) {

  $http.get(....).then(.....);

}

 

2、provider  

Now let myself to customize a provider

// 方法 1
$provide.provider('test', {

   n:1;

   $get: function () {

      return n;

    };

});

// 方法 2
$provide.provider('test', function () {

   this.n = 2;

   this.$get = function () {

   return n;

};

});

// 使用
app.controller('MainCtrl', function ($scope, test) {
    $scope.test = test;
});

  

Let's look at provider's internal implementation code

function provider(name, provider_) {

  if (isFunction(provider_)) {

      provider_ = providerInjector.instantiate(provider_);

  }

   if (!provider_.$get) {

       throw Error('Provider ' + name + ' must define $get factory method.');

   }

   return providerCache[name + providerSuffix] = provider_;

}

 

Provider can see the basic principle to a single embodiment is implemented by injecting $ get method, it is obtained by the use of $ get the result of execution.

3, factory


What if every time to write a $ get is not too much trouble? OK, so we have a factory. factory can be said provider variant of the method the second parameter is the content of $ get in.

// 定义 factory

$provide.factory('dd', function () {

   return new Date();

});

// 使用

app.controller('MainCtrl', function ($scope, dd) {

    $scope.mydate = dd;

});

  


The factory source code:

function factory(name, factoryFn) {

 return provider(name, {

   $get: factoryFn

});

}

  

4、service


In the case of the factory, we still need a new object is returned, and the service is even simpler, this step will help you save, his second argument is that you want to return the object class, which is new to you, oh work you do not have to do. Cool enough, right?

// define service

$provide.service('dd', Date);


The following is a source code of service:

function service(name, constructor) {

  return factory(name, ['$injector', function($injector) {

       return $injector.instantiate(constructor);

   }]);
}

 

Then bring the code to streamline factory and service but also the loss of some features. service provider may be defined by the configuration module config.

 

Three, AngularJS dynamically add elements and remove elements

 

$scope.userName='Welcome to Angular World!';
$scope.test = function test(){
console.log('Angular 动态添加元素');
}

//通过$compile动态编译html
var html="<div ng-click='test()'>}</div>";
var template = angular.element(html);
var mobileDialogElement = $compile(template)($scope);
angular.element(document.body).append(mobileDialogElement);

// remove移除创建的元素
var closeMobileDialog = function () {
if (mobileDialogElement) {
  mobileDialogElement.remove();
}

 

Four, AngularJS event broadcast and reception 

 

Send message:  $ $ scope EMIT (name, Data) or $ scope $ broadcast (name, data );..

Receiving a message : $ scope.on (name, function ( event, data) {});

Difference:  $ EMIT broadcast to the parent controller $ broadcast broadcasting to sub-controller

 

broadcast from a sender to a sub-scope of his broadcast an event.

Here is ParentController send, ParentController and ChildController will receive, but will not receive MainController

 

$ Emit radio to the parent controller, the parent controller can receive the message

There are two parameters $ ON function (event, msg) The first argument is the event object, the second parameter is the received message information

 

angular.module('onBroadcastEvent', ['ng'])
     .controller('MainController', function($scope) {
       $scope.$on('To-MainController', function(event,msg) {
         console.log('MainController received:' + msg);
       });
     })
     .controller('ParentController', function($scope) {
       $scope.click = function (msg) {
         $scope.$emit('To-MainController',msg + ',from ParentController to MainController');
         $scope.$broadcast('To-ChildController', msg + ',from ParentController to ChildController');
         $scope.$broadcast('To-BrotherController', msg + ',from ParentController to BrotherController');
       }
     })
     .controller('ChildController', function($scope){
       $scope.$on('To-ChildController', function(event,msg) {
         console.log('ChildController received:' + msg);
       });
     })
     .controller('BrotherController', function($scope){
       $scope.$on('To-BrotherController', function(event, msg) {
         console.log('BrotherController received:' + msg);
       });
     });

 

Five, AngularJS Promise Deferred examples

var app = angular.module('app', ['autocomplete']);
app.factory('Suggestion',
function($http, $q, $timeout){
  var suggestion = new Object();
  suggestion.getData = function(keyword) {
    var deferred = $q.defer();
    $http.get('http://codesearch.sinaapp.com/search.php',
    }).success(function(data){
      deferred.resolve(data);
    });
    return deferred.promise;
  }
  return suggestion;
});
app.controller('MySuggestionCtrl',
function($scope, $sce,Suggestion){
  $scope.autoComplete = function(keyword){
    if(keyword){
        Suggestion.getData(keyword).then(function(data){
        var dataList = data.split('|');
        $scope.dataList = dataList;
      });
    }
  }
});

 Promise multiple instances:

var data2="222";
var promises = [];
var deffered1  = $q.defer();
var deffered2  = $q.defer();
$timeout(function(){
  deffered1.resolve(data1);
},2000);
$timeout(function(){
  deffered2.resolve(data2);
},2000);
promises.push(deffered1.promise);
promises.push(deffered2.promise);
 $q.all(promises).then(function(data){
    console.log(data);
});

Output: [ "111", "222"] This object is an array of the same order as the order push

  

Six, AngularJS global scope scope communicate with Isolate

 

A, scope scope

1, AngularJS, the sub-scope properties and methods of its parent scope usually inherited through JavaScript prototype inheritance. There is one exception: use the scope in directive: {...}, the scope of this approach is to create a separate "Isolate" scopes, scopes it has a parent, but not its parent scope prototype chain, We will not inherit the parent scope prototype. Commonly used in this way define the scope directive reusable assembly configured.

2, if we visit a parent scope defined in the sub-scope property, JavaScript first look for the property in the child scope, and then look for from a parent did not find the scope of the prototype chain, if not found will again father up a prototype chain of scopes to find. In AngularJS, the tip of the scope of the prototype chain is $ rootScope, JavaScript seeking up to $ rootScope.

3, scope: {...} - directive to create a separate "Isolate" scope, no prototype inheritance. This is the best choice to create reusable components directive. Because it does not directly access / modify the properties of the parent scope, no unexpected side effects.

 

Two, Isolate scope quote modifiers

1, = or = attr "Isolate" attribute of the parent scope scope attributes two-way binding, any modifications that affect the other party, which is the most common way;

2, @ or @attr "Isolate" attribute and the parent attribute scope scope way binding, i.e., "Isolate" Scope parent scope only read value, and the value of type String forever;

3, & or & attr "Isolate" Scope the parent scope attribute packaged into a function, so as to read and write functions parent scope properties, the parse package is $

 

Three, directive data transfer and communication with the controller

1, the parent controller monitor global scope (parent scope) variables, and broadcast events to the child scope (directive scope, each has its own independent scope directvie scope)

2, directive defines the local scope, by = @, & (Method) character display reference global scope

3, directive scope (sub-scope) properties of global scope by reference parent [$ scope. $ Parent.xxx]

4, directive monitor global scope variables change, by $ scope. $ Parent. $ Watch method

 

Fourth, examples to explain

http://www.cnblogs.com/hubcarl/p/4202053.html

 

七、AngularJS $apply vs $digest

  • $ apply ng will enter $digest cycleand start traversing from $ rootScope (depth-first) inspection data changes.
  • $ Digest will only examine the scope and its sub-scope, when you are sure that they only affect the current operation, with $ digest may slightly improve performance.
  • Unnecessary operation, into $timeoutwhich delay execution.
  • If you do not involve data changes, you can also add a third parameter false, avoid calling $apply.
  • directive executed $evalAsync, it will be in operation after the angular DOM, browser rendering execution before.
  • controller executed $evalAsync, will be executed before the angular operating DOM, generally do not use it.
  • And use $timeout, will be executed after the browser rendering.
  • Time required by the second parameter may be set to 0.
    $http.get('http://path/to/url').success(function(data){
      $scope.name = data.name;
      $timeout(function(){
        //do sth later, such as log
      }, 0, false);
    });
    

     

    Details: https://github.com/atian25/blog/issues/5

 

Eight, AngularJS Directive learning examples

 

1, restrict it limits the directive specified declaratively. If omitted, directive will only allow a property declaration

E - element name: <my-directive> </

A - 属性名: <div my-directive="exp"></div>

C - class名: <div class="my-directive:exp;"></div>

M - 注释 : <!-- directive: my-directive exp -->

2, dialog example

<!DOCTYPE html>
 
<html ng-app="Dialog">
 
<head>
 
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 
  <title>directive-dialog</title>
 
  <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
 
  <script src="../../sea-modules/angular/angularjs/1.1.5/angular.js"></script>
 
</head>
 
<body>
 
<div ng-controller="MyCtrl">
 
  <button ng-click="show=true">show</button>
 
  <dialog title="Hello }"
 
          visible="}"
 
          on-cancel="show=false;"
 
          on-ok="show=false;methodInParentScope();">
 
    <!--上面的on-cancel、on-ok,是在directive的isoloate scope中通过&引用的。
 
    如果表达式中包含函数,那么需要将函数绑定在parent scope(当前是MyCtrl的scope)中-->
 
    Body goes here: username:} , title:}.
 
    <ul>
 
      <!--这里还可以这么玩~names是parent scope的-->
 
      <li ng-repeat="name in names">}</li>
 
    </ul>
 
  </dialog>
 
</div>
 
<script type="text/javascript">
 
  var myModule = angular.module("Dialog", []);
 
  myModule.controller("MyCtrl", function ($scope) {
 
    $scope.names = ["name1", "name2", "name3"];
 
    $scope.show = false;
 
    $scope.username = "carl";
 
    $scope.title = "parent title";
 
    $scope.methodInParentScope = function() {
 
      alert("scope里面通过&定义的东东,是在父scope中定义!!。。。");
 
    };
 
  });
 
  myModule.directive('dialog', function factory() {
 
    return {
 
      priority:100,
 
      template:['<div ng-show="visible">',
 
        '    <h3>}</h3>',
 
        '    <div class="body" ng-transclude></div>',
 
        '    <div class="footer">',
 
        '        <button ng-click="onOk()">OK</button>',
 
        '        <button ng-click="onCancel()">Close</button>',
 
        '    </div>',
 
        '</div>'].join(""),
 
      replace:false,
 
      transclude: true,
 
      restrict:'E',
 
      scope:{
 
        title:"@",//引用dialog标签title属性的值
 
        onOk:"&",//以wrapper function形式引用dialog标签的on-ok属性的内容
 
        onCancel:"&",//以wrapper function形式引用dialog标签的on-cancel属性的内容
 
        visible:"@"//引用dialog标签visible属性的值
 
      }
 
    };
 
  });
 
</script>
 
</body>
 
</html>

 

Nine, AngularJS Notes and Issues Summary (Continued)

Beware that using Note angular.module ( 'myModule', []) and angular.module ( 'myModule') using

angular.module('myModule', []) will create the module myModule and overwrite any existing module namedmyModule.

>>> angular.module ( 'myModule', []) Create a new module, overwrite an existing module

Use angular.module('myModule') to retrieve an existing module.

>>> angular.module ( 'myModule') pointing to already existing module

 

Reproduced in: https: //www.cnblogs.com/hubcarl/p/4207909.html

Guess you like

Origin blog.csdn.net/weixin_34072159/article/details/93817358