Angular controller as syntax vs scope

Source: Internet
Author: User

What we want to share with you today is that angular has introduced the new syntax Controller as since version 1.2. Before binding angular to the view, we must use a direct scope object. For the controller, we must also inject the $ scope service. As follows:

angular.module("app",[]).controller("demoController",["$scope",function($scope){    $scope.title = "angualr"; }])<div ng-app="app" ng-controller="demoController">    hello : {{title}} !</div>

Some people think that even so, our controller is not POJO enough and it is not friendly to coffescript fans, therefore, angular brings me a new syntactic sugar in 1.2, which is the syntactic sugar of the controller as described in this article. Modifying the demo above will become:

angular.module("app",[]).controller("demoController",[function(){    this.title = "angualr";}])<div ng-app="app" ng-controller="demoController as demo">     hello : {{demo.title}} !</div>

Here we can see that the controller no longer has $ scope injection. It feels like the controller is a very simple plane JavaScript Object and there is no difference. In addition, a demoController as demo is added to the view and an alias is assigned to the controller. In the later view template, the alias is used to access the data object.

You may ask why you need this. It's not just a syntactic sugar. Don't worry. We will analyze the difference between $ scope and $ scope later. Before that, let's take a look at the implementation of angular source code to facilitate our analysis:

The following is a piece of code from angular: Starting from line 1 (the number of lines can only be valid during writing)

if (directive.controllerAs) {         locals.$scope[directive.controllerAs] = controllerInstance;  }

If you want to see more complete code please slam here https://github.com/angular/angular.js/blob/c7a1d1ab0b663edffc1ac7b54deea847e372468d/src/ng/compile.js.

What we can see from the code above is that angular only creates a new object attribute on the scope using the controller object instance with its as Alias. That's just a line of code!

Don't worry. Since it is syntactic sugar, there must be a reason for its appearance. let's compare it with $ scope:

Before that, I discussed my views in the angularjs group and got good feedback. So I have recorded and shared this article.

The method for writing controller as is as follows:

angular.module("app",[]) .controller("demoController",[function(){        var vm = this;        vm.title = "angualr";        return vm; }])

Its advantages include:

  1. Defining a vm will help us avoid this pitfall of JavaScript.

  2. If angular of a certain version no longer supports controller as, you can easily inject $ scope and change it to var vm = $ scope;

  3. Because $ scope is no longer injected, the controller's more POJO is a very common JavaScript Object.

  4. Because $ scope is absent, and the controller instance will become an attribute on the scope, we can no longer use special methods such as $ watch, $ emit, and $ on in the controller, this is because these things often do not appear in the controller and give everyone a warning for better control. However, if you cannot use it, you can obtain the unanimous consent of the project team to return the controller to $ scope.

  5. Because the controller instance will only be an attribute of $ scope, all the fields in the view template will be on a referenced attribute, which can avoid the pitfall of the JavaScript prototype chain inheritance for the value type. Participate in https://github.com/angular/angular.js/wiki/Understanding-Scopes.

  6. Controller as is more friendly to coffescript and liveScript. 7. Each field method defined in the template will be stored in the scope on the reference of the controller as Alias, so there will be no name conflict issues in the controller inheritance.

Note: For route, there is also a controllerAs attribute that can be set. The angular doc file in the following code:

angular.module('ngViewExample', ['ngRoute', 'ngAnimate'],     function($routeProvider, $locationProvider) {    $routeProvider.when('/Book/:bookId', {      templateUrl: 'book.html',      controller: BookCntl,      controllerAs: 'book'    });    $routeProvider.when('/Book/:bookId/ch/:chapterId', {      templateUrl: 'chapter.html',      controller: ChapterCntl,      controllerAs: 'chapter'    });    // configure html5 to get links working on jsfiddle         $locationProvider.html5Mode(true);     });

This is today. Thank you.


This article from the "wolf" blog, please be sure to keep this source http://whitewolfblog.blog.51cto.com/3973901/1345308

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.