如何使用Controller As表示法访问父属性

ben*_*gro 26 angularjs

我在我的视图中使用Controller如下:

<body ng-controller="MainCtrl as main">
   <div ng-controller="ChildCtrl as child">
      {{ main.parentValue }} + {{ child.childValue }}
   </div>
</body>
Run Code Online (Sandbox Code Playgroud)

像这样定义我的控制器:

app.controller('MainCtrl', function($scope) {
   this.parentValue = 'Main';
});

app.controller('ChildCtrl', function($scope) {
   this.childValue = 'Child';
   // I want to access the property of the parent controller here
});
Run Code Online (Sandbox Code Playgroud)

ChildCtrl如何设置MainCtrl的name属性?这里是普兰克.

使用$ scope表示法,我可以从子控制器访问$ scope.parentValue.如何使用Controller As表示法实现相同的功能?

JME*_*JME 20

因为您使用"控制器作为"符号,所以您ChildCtrl可以访问MainCtrl使用$scope.main,例如$scope.main.name.

请参阅下面的我的代码段.

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  this.name = 'Main';
  this.test = {};
});

app.controller('ChildCtrl', function($scope) {
  this.name = 'Child';
  alert($scope.main.name);
});
Run Code Online (Sandbox Code Playgroud)
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-controller="MainCtrl as main">
  <div ng-controller="ChildCtrl as child">
    {{ main.name }} + {{ child.name }}
  </div>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)


小智 8

你不应该混淆"控制器为"和$ scope使用.要更新父作用域中的数据,您可以/应该使用服务.

示例:从任何子控制器中更改页面标题:

app.service("SiteService", function () {
    return {
        title: "Page title";
    }
}


app.controller ("ParentCtrl", function (SiteService) {
    this.site = SiteService;
}

app.controller ("ChildCtrl", function (SiteService) {
    SiteService.title = "New Title";
}
Run Code Online (Sandbox Code Playgroud)

和你的模板

<html ng-app="someApp" ng-controller="ParentCtrl as site">
    <head>
         <title>{{site.title}}</title>
    </head>
</html>
Run Code Online (Sandbox Code Playgroud)

这种方法的主要优点是:将public mutable与私有属性分开.

  • 当问题询问访问父控制器数据时,这只是看起来很奇怪的全局变量.如果你有多对ParentCtrl + ChildCtrl实例,它会立即引起麻烦. (5认同)