【问题标题】:modify main controller $scope from ng-include controller从 ng-include 控制器修改主控制器 $scope
【发布时间】:2018-02-10 01:12:04
【问题描述】:

我的页面中包含他的控制器的标题视图:

<div ng-include="'header.html'" ></div>

标题包含一个动作调用,如保存、更新...我希望当用户单击标题动作时更新我的​​主控制器。

但我无法从包含 ng 的页面访问和修改主控制器 $scope

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

app.controller('MainCtrl', function($scope) {
  $scope.value = 'first value';

});

app.controller('HeaderCtrl', function($scope) {
  $scope.header = 'from header';

  $scope.update = function(){
    $scope.$parent.value = 'new value';
  }
});

我创建了一个 plunker 演示来说明问题

http://plnkr.co/edit/xeMD2NxUdb6g8CEcRnFu?p=preview

【问题讨论】:

    标签: javascript angularjs scope prototype angularjs-ng-include


    【解决方案1】:

    在子作用域中从父作用域更新值时,我通常使用以下其中一种:

    1. 将对象传递给子对象并更新对象内部的属性
    2. 将函数传递给子作用域并调用此函数来更新值。

    在您的示例中,如果您使用选项 (1),它将是这样的:

    app.js 文件

    app.controller('MainCtrl', function($scope) {
      $scope.value = {
        data: 'first value'
      };
    });
    
    app.controller('HeaderCtrl', function($scope) {
      $scope.header = 'from header';
    
      $scope.update = function(){
        $scope.$parent.value.data = 'new value';
      }
    });
    

    没有使用ng-include,但是可以看一下this example passing function to a component to update data

    要进一步低估 AngularJS 中的作用域,您可以阅读What are the nuances of scope prototypal/prototypical inheritance in AngularJS?

    【讨论】:

    • 没问题。有很多问题,我很乐意提供帮助。如果您有兴趣,请参阅 John Papa 的 Angular 1 Style Guide。在 AngularJS 中编写更好的代码是一本不错的读物,他还解释了为什么要这样做。
    【解决方案2】:

    在您的具体情况下,您可以使用:

    $scope.$parent.$parent.value = 'new value';
    

    检查Modified plunkr

    但真正的解决方案是使用designated property for each controller,或者更好的是使用controller as 语法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      相关资源
      最近更新 更多