Steffi
Steffi

Reputation: 7057

How to update parent scope in AngularJS?

I tried to update my parent scope from the child controller using two solutions but I can't make it work. apply() didn't work

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; }); 
     }
}]);

Upvotes: 2

Views: 1137

Answers (2)

maurycy
maurycy

Reputation: 8465

Controllers have separate scope but there is a few way to communicate

Upvotes: 1

Diana Nassar
Diana Nassar

Reputation: 2303

You can't update primitive attributes in the parent object, only object attributes. So you need to use:

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

Upvotes: 1

Related Questions