angular语法:Controller As

这个东东我觉得很好哟。

数据可以在同一个页面的不同的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.

转载于:https://www.cnblogs.com/aguncn/p/5778839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值