如何使用Controller As表示法访问父级属性 [英] How to access parent property using Controller As notation

查看:67
本文介绍了如何使用Controller As表示法访问父级属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中的使用方式如下:

I'm using the Controller as in my view as follows:

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

这样定义我的控制器:

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
});

ChildCtrl如何设置MainCtrl的name属性?在这里 Plunkr .

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

Using the $scope notation, I could have accessed $scope.parentValue from the child controller. How can the same functionality be achieved using the Controller As notation?

推荐答案

由于使用的是"controller as"符号,因此在ChildCtrl中,您可以使用$scope.main(例如,$scope.main.name)访问MainCtrl.

Since your using the "controller as" notation, witin your ChildCtrl you can access the MainCtrl using $scope.main, for example $scope.main.name.

请在下面查看我的代码段.

See my snippet below.

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);
});

<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>

这篇关于如何使用Controller As表示法访问父级属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆