2

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; }); 
     }
}]);
Steffi
  • 6,835
  • 25
  • 78
  • 123
  • `$scope.$parent.tab_selected = 2;` – Arun P Johny Jun 19 '14 at 09:14
  • Various ways, but one easy way is to use an object or array in the parent scope (this will be instantly available across both parent and child scope - http://stackoverflow.com/questions/16972976/angular-js-propagate-child-scope-variable-changes-to-parent-scope – Mark Walters Jun 19 '14 at 09:15
  • For the Love of god :( this is the 10000nth , ALWAYS USE A DOT in angular $scope properties – Milad Jun 19 '14 at 11:34
  • @xe4me What do you mean ? – Steffi Jun 19 '14 at 11:58
  • @Steffi it's been suggested by angular team and of course its true that always use a DOT , that means to stick anything to $scope, E.g $scope.myVariable , instead of using a primitive variable , alvays use an object , like : $scope.variables.myVariable !! (You see DOT ? - that means always define objects instead of primitives) – Milad Jun 19 '14 at 12:43
  • If you look into angular questions , almost half of them will be solved(or has been solved) with using object instead of primitives; that's embarassing – Milad Jun 19 '14 at 12:49

2 Answers2

1

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

maurycy
  • 8,455
  • 1
  • 27
  • 44
1

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;
Diana Nassar
  • 2,303
  • 14
  • 17