【问题标题】:what's the different with using $scope and explicitly using ctrl as namespace? [duplicate]使用 $scope 和显式使用 ctrl 作为命名空间有什么不同? [复制]
【发布时间】:2017-02-10 08:33:07
【问题描述】:

我们可以在angularJS中使用$scope作为命名空间

    angular.module('myApp',[])
           .controller("myController", function($scope){
            $scope.info = "Hello";
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
    <div ng-controller="myController">
         <input type="text" ng-model="info">
         {{info}}
    </div>
  </body>

或者我们可以在controller 中显式使用this,并在视图中使用控制器名称作为命名空间,例如:

    angular.module('myApp',[])
           .controller("myController", function(){
            this.info = "Hello";
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="myController as ctrl">
         <input type="text" ng-model="ctrl.info">
         {{ctrl.info}}
    </div>
</body>

我的问题是有什么区别以及选择使用什么?

【问题讨论】:

    标签: angularjs scope


    【解决方案1】:

    链接Angularjs "Controller as" or "$scope" 中的这个答案解释了controllerAs vs $scope。

    另外,根据我自己的经验,我更喜欢 controllerAs 语法。因为,我通常将动态数据添加到对象数组中。

    使用 $scope 选项时,ng-repeat 无法在将新数据推送到 Array 时自行刷新,例如 $scope.dataArray

    当使用 controllerAs 语法时,每当我将数据推送到 dataArray 对象时,ng-repeat 都会将新数据添加到视图中。

    这主要是因为在使用 $scope 语法时,对数组的任何更改都会创建一个新的引用。但是,使用 controllerAs 语法,数组引用始终保持不变。

    参考ng-repeat not updating on update of array

    【讨论】:

    • 谢谢@Neerajkummar,我检查了推荐的答案。那么,我们推荐使用“Controller as”语法对吗?使用 $scope 以外的语法时,我还应该注意其他一些坑吗?因为我读了developer guide,它很少提到使用Controller as语法,但大多数例子选择了$scope
    • @Neerajkummar,搜索 Controller a vs scope 给我一些很好的重复问题,将深入研究这些问题并关闭此问题,感谢您的努力并为您带来的麻烦感到抱歉。
    • 很高兴为@armnotstrong 提供帮助!到目前为止,我还没有看到使用 ControllerAs 语法的任何问题。在使用自定义指令时,最初我发现它很困难,因为我不知道如何在自定义指令中使用 ControllerAs。但是总有 stackoverflow 可以帮助我们。干杯!!!
    猜你喜欢
    • 2013-09-25
    • 2020-01-07
    • 2011-12-10
    • 2015-02-24
    • 2014-09-22
    • 2020-11-24
    • 2011-01-20
    • 2012-01-30
    • 1970-01-01
    相关资源
    最近更新 更多