加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何使用Controller As符号访问父属性

发布时间:2020-12-17 08:26:16 所属栏目:安全 来源:网络整理
导读:我正在使用Controller,如下所示: body ng-controller="MainCtrl as main" div ng-controller="ChildCtrl as child" {{ main.parentValue }} + {{ child.childValue }} /div/body 定义我的控制器: app.controller('MainCtrl',function($scope) { this.pare
我正在使用Controller,如下所示:
<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符号来实现相同的功能?

由于您使用“控制器”符号,因此在ChildCtrl中,您可以使用$ scope.main访问MainCtrl,例如$ 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);
});
<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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读