angular语法:Controller As

时间:2024-07-22 12:37:08

这个东东我觉得很好哟。

数据可以在同一个页面的不同的controller之间*穿梭。。。

当然,

https://thinkster.io/a-better-way-to-learn-angularjs/controllers

这个网址也不错哟。。。

https://thinkster.io/a-better-way-to-learn-angularjs

Controller As Syntax

While everything we've created in this example so far works fine, a possible issue we can come accross as our application grows is when we start nesting controllers. Since each controller gets assigned their own scope, controllers that are nested can have trouble accessing variables from the parent scope. Specifically when data is being read from a child controller, where the value is directly assigned to the parent $scope and not namespaced within an object (accessing $scope.data.message will work from a child controller but accessing $scope.message can break). The rule of thumb is to always have a dot when referencing variables from controllers in your angular expressions. We can enforce this by using the "controller as" syntax. This makes it so that your controllers can be directly referenced within the view. The "controller as" syntax is generally the preferred syntax for controllers.

Read this post on the "controller as" syntax

Now let's update our code to use the "controller as". Since our scope becomes the this keyword in our controller, we'll need to create a reference to this so that we don't lose context of our controller when we create/call functions within our controller.

Read the MDN reference for the this keyword in javascript

Create a reference to this in our controller.

angular.module('app').controller('MainCtrl', function ($scope){
  var self = this;

Remove $scope from our controller dependency, and use self instead of $scope.

angular.module('app').controller('MainCtrl', function (){
  var self = this;

  self.message = 'hello';

  self.changeMessage = function(message){
    self.message = message;
  };
});

Now, let's update our view to use the "controller as" syntax.

<div ng-controller="MainCtrl as main">
  <p>{{ main.message }}</p>
  <form ng-submit="main.changeMessage(main.newMessage)">
    <input type="text" ng-model="main.newMessage">
    <button type="submit">Change Message</button>
  </form>
</div>

Now all of our variables in our Angular expressions contain a dot, and we're able to directly reference our controllers so that when we have nested or multiple nested controllers, we can access variables directly instead of using $parent.