【问题标题】:How to access parent property using Controller As notation如何使用 Controller As 表示法访问父属性
【发布时间】:2014-12-06 04:59:15
【问题描述】:

我正在使用控制器,如下所示:

<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 表示法如何实现相同的功能?

【问题讨论】:

  • 支持您的问题...我认为这是一个合理的问题,不确定谁/为什么会反对它。
  • 这个问题可能是基本的,但仍然是合法的。在其他情况下,对父范围的访问相对直接。但是,当使用“控制器作为”表示法时,它不是。我认为这个社区的目的是互相帮助,无论我们的问题是否被更有经验的开发人员认为是基本的。只是我的两分钱。 :-)
  • @bengro 也许你可以看看这个,这可能对你有帮助。只需添加一个链接到另一个解释清楚的链接,并为未来的访问者提供更好的答案。stackoverflow.com/questions/21453697/…

标签: angularjs


【解决方案1】:

由于您使用“controller as”表示法,因此您可以通过ChildCtrl 访问MainCtrl,使用$scope.main,例如$scope.main.name

请看下面我的 sn-p。

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>

【讨论】:

    【解决方案2】:

    您不应该混淆“controller as”和 $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";
    }
    

    还有你的模板

    <html ng-app="someApp" ng-controller="ParentCtrl as site">
        <head>
             <title>{{site.title}}</title>
        </head>
    </html>
    

    这种方法的主要优点:您可以将公共可变属性与私有属性分开。

    【讨论】:

    • 当问题询问有关访问父控制器数据的问题时,这只不过是看起来很漂亮的全局变量。如果您有一对以上的 ParentCtrl+ChildCtrl 实例,它将立即引起麻烦。
    【解决方案3】:

    将数据放入$scope 是执行此操作的角度方式。您还可以从服务中设置/获取数据,然后很容易将其包含到任一控制器中。

    观看此视频:https://egghead.io/lessons/angularjs-sharing-data-between-controllers

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 2023-03-23
      • 2016-02-11
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      相关资源
      最近更新 更多