代码取自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’,在指令中.谢谢
解决方法
这是我的简单指令代码:
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
@H_301_53@
that they could just usethis
同样从他们的own website你可以阅读这个设计选择背后的动机,
Using controller as makes it obvIoUs which controller you are
@H_301_53@
accessing in the template when multiple controllers apply to an
element希望能帮助到你.