如何在不更改视图的情况下将子控制器范围与父控制器范围隔离?

时间:2016-07-05 07:33:47

标签: angularjs angularjs-scope angularjs-controller

单击父按钮也可以更改子项而不是子项按钮。 我需要改变这种行为,以任何黑客或其他方式隔离范围。

子控制器不会从父控制器继承,并且必须有自己的范围!



angular
  .module('app', [])
  .controller('ParentCtrl', function() {})
  .controller('ChildCtrl', function() {})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=app>
  <div ng-controller=ParentCtrl>
    <button ng-click="text='clicked'">
      {{text || 'parent'}}
    </button>
    <div ng-controller=ChildCtrl>
      <button ng-click="text='clicked'">
        {{text || 'child'}}
      </button>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/nizami/oLwbktz9/

3 个答案:

答案 0 :(得分:1)

angular
  .module('app', [])
  .controller('ParentCtrl', ['$scope', function($scope) {
  $scope.text = null;
  }])
  .controller('ChildCtrl', ['$scope', function($scope) {
  $scope.text = null;
  }])

答案 1 :(得分:1)

检查更新的plunkr ..我希望你能得到你的回答

https://jsfiddle.net/oLwbktz9/6/

<div ng-controller=ParentCtrl>
  <button ng-click="text='clicked'">
    {{text || 'parent'}}
  </button>
    </div>
  <div ng-controller=ChildCtrl>
    <button ng-click="text='clicked'">
      {{text || 'child'}}
    </button>
</div>

答案 2 :(得分:0)

只需更改子控制器范围变量即可。 控制器总是从父控制器继承范围。在指令中,您可以选择创建隔离范围。

<div ng-controller=ParentCtrl>
  <button ng-click="text='clicked'">
    {{text || 'parent'}}
  </button>
  <div ng-controller=ChildCtrl>
    <button ng-click="text2='clicked'">
      {{text2 || 'child'}}
    </button>
  </div>
</div>