使用Controller As方法访问继承的范围

使用Controller As方法访问继承的范围,第1张

使用Controller As方法访问继承的范围

经过研究,我得出以下认识:

Controller-As方法不能代替使用

$scope
。两者都有其位置,可以/应该明智地一起使用。

  1. $scope
    确实执行该名称所隐含的含义:即,它在上定义了ViewModel属性
    $scope
    。这最适合与可使用
    $scope
    来驱动自己的逻辑或对其进行更改的嵌套控制器共享范围。
  2. 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>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5674007.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存