加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:16:27 所属栏目:安全 来源:网络整理
导读:学习角度所以有些时候事情不清楚,阅读文章角度.在这里,我坚持要了解这个关键字Controller和controllerAs在指令中的用法或重要性. 代码取自http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html app.controller('Som
学习角度所以有些时候事情不清楚,阅读文章角度.在这里,我坚持要了解这个关键字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

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

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

希望能帮助到你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读