【问题标题】:Angular access/change nested ng-controller variable?角度访问/更改嵌套的 ng-controller 变量?
【发布时间】:2015-08-28 21:10:51
【问题描述】:

我有一个包含在多个页面上的局部视图。 Partial 视图位于 NgController 上。 当我在另一个嵌套控制器中时,有没有办法可以访问该特定嵌套控制器的范围变量?

例如:

<div ng-controller="fooController">

    <a ng-click="changeScopeVariableOfBarController()">Click!</a>

    <div ng-controller="barController">
        {{ thisHasToChangePlease }}
    </div>
</div>

这可能吗?我不知道怎么做。我将部分视图包含在 php 的包含中,所以我不使用模板。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    如果您有一个可重用的“组件”(模板 + 功能),您可以将其重构为指令而不是模板 + 控制器。然后,使用带有参数的隔离作用域,您可以让外部世界以这种方式更改指令的内部。

    http://plnkr.co/edit/6JYVucuizmPkyt2CLQtr?p=preview

    index.html

    <div ng-controller="fooController">
      <div>variable: {{ variable }}</div>
      <button ng-click="changeScopeVariableOfBarController()">Click to increment variable on both scopes!</button>
      <bar this-has-to-change-please="variable"></bar>
    </div>
    

    bar.html

    <div>
        thisHasToChangePlease: {{ thisHasToChangePlease }}
    </div>
    

    app.js

    app.controller('fooController', function($scope) {
      $scope.variable = 1;
    
      $scope.changeScopeVariableOfBarController = function () {
        $scope.variable++;
      };
    });
    
    app.controller('barController', function ($scope) {
    
    });
    
    app.directive('bar', function () {
      return {
        restrict: 'E',
        scope: {
          thisHasToChangePlease: '='
        },
        controller: 'barController',
        templateUrl: 'bar.html'
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2015-09-15
      • 2019-06-24
      相关资源
      最近更新 更多