angularjs – Angular Controller和controllerAs指令中的关键字用法

前端之家收集整理的这篇文章主要介绍了angularjs – Angular Controller和controllerAs指令中的关键字用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_2@
学习角度所以有些时候事情不清楚,阅读文章角度.在这里,我坚持要了解这个关键字Controller和controllerAs在指令中的用法或重要性.

代码取自http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html

app.controller('SomeController',function () {
  this.foo = 'bar';
});

app.directive('someDirective',function () {
  return {
    restrict: 'A',controller: 'SomeController',controllerAs: 'ctrl',template: '{{ctrl.foo}}'
  };
});

我想知道这两个关键字在指令中的重要性,它们是控制器:’SomeController’和controllerAs:’ctrl’,

请告诉我,如果我们不使用这两个关键字控制器:’SomeController’,和controllerAs:’ctrl’,那么会发生什么或会更糟?

请帮助我理解这个关键字控制器的用法或重要性:’SomeController’和controllerAs:’ctrl’,在指令中.谢谢

解决方法

看看这个 plunkr code

这是我的简单指令代码

angular.module('app',[])

.directive('someDirective',function () {
  return {
    scope: {},controller: function ($scope) {
      this.name = 'Pascal';
      $scope.color = 'blue';
    },template: '<div>name: {{ctrl.name}} and Color: {{color}}</div>'
  };
});

和HTML

<body ng-app="app">
   <some-directive />
</body>

因此,正如您所看到的,如果您需要访问在控制器中针对此关键字定义的某个变量,则必须使用controllerAs.但如果它是针对$scope对象定义的,您只需使用其名称即可访问它.

例如,您可以使用{{color}}获取变量颜色,因为它是根据$scope定义的,但您必须使用{{ctrl.name}},因为“name”是针对此定义的.

我认为没有太大的区别,正如this answer所说,

Some people don’t like the $scope Syntax (don’t ask me why). They say
that they could just use this

@H_301_53@

同样从他们的own website你可以阅读这个设计选择背后的动机,

Using controller as makes it obvIoUs which controller you are
accessing in the template when multiple controllers apply to an
element

@H_301_53@

希望能帮助到你.

@H_403_2@

猜你在找的Angularjs相关文章