经过研究,我得出以下认识:
Controller-As方法不能代替使用
$scope。两者都有其位置,可以/应该明智地一起使用。
$scope
确实执行该名称所隐含的含义:即,它在上定义了ViewModel属性$scope
。这最适合与可使用$scope
来驱动自己的逻辑或对其进行更改的嵌套控制器共享范围。- Controler-As将整个控制器对象定义为具有命名范围的ViewModel(通过控制器的别名)。如果View决定是否要引用特定的控制器ViewModel,则此方法仅在View(而非其他控制器)中效果最佳。
这是一个例子:
var app = angular.module('myApp', []);// Then the controllers could choose whether they want to modify the inherited scope or not:app.controller("ParentCtrl", function($scope) { this.prop1 = { v: "prop1 from ParentCtrl" }; $scope.prop1 = { v: "defined on the scope by ParentCtrl" }; }) .controller("Child1Ctrl", function($scope) {}) .controller("Child2Ctrl", function($scope) { // here, I don't know about the "pc" alias this.myProp = $scope.prop1.v + ", and changed by Child2Ctrl"; });<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script><body ng-app="myApp"> <div ng-controller="ParentCtrl as pc"> <div ng-controller="Child1Ctrl"> <div>I know about the "pc" alias: {{pc.prop1.v}}</div> </div> <div ng-controller="Child2Ctrl as ch2"> <div>I only care about my own ViewModel: {{ch2.myProp}}</div> </div> </div>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)