如何在AngularJS中更新父范围?

时间:2014-06-19 09:09:03

标签: javascript angularjs angularjs-scope

我尝试使用两种解决方案从子控制器更新我的父作用域,但我无法使其工作。 apply()没有工作

HTML:

<div ng-controller="ControllerA">
   <div ng-show="tab_selected == 1">Content1</div>
   <div ng-show="tab_selected == 2">Content2</div>
   <div ng-controller="ControllerB">
      <span ng-click="updateScope()"></span>
   </div>
</div>

JS:

app.controller('ControllerA', ['$scope', 
  function ($scope) {
     $scope.tab_selected = 1;
}]);

app.controller('ControllerB', ['$scope', 
  function ($scope) {
     $scope.updateScope = function(){
        $scope.tab_selected = 2;
        // $scope.apply(function(){  $scope.tab_selected = 2; }); 
     }
}]);

2 个答案:

答案 0 :(得分:1)

控制器具有单独的范围,但有几种通信方式

答案 1 :(得分:1)

您无法更新父对象中的原始属性,只能更新对象属性。所以你需要使用:

$scope.someObject= {};
$scope.someObject.tab_selected= 2;