angularjsangularjs-directiveangularjs-ng-switch

ngSwitch does not update when data model change


I'm new to Angular and trying to write some simple app. I have problem using ngSwitch to switch the according directive on demand as follow.

the html markups :

main html file: directiveOne:

.directive('directiveOne',function(){
      return {
      restrict:"AE",
      replace:true,
      template:"<div>this is directive one</div>",
      controller:"Dir1Controller",
      }
})
.directive('directiveTwo',function(){
      return {
      restrict:"AE",
      template:"<div>this is directive 2</div>,
      controller:"Dir2Controller"
      }
})

and a service to share data between controller.

.factory('ShareDataFct',function($rootScope){
      var srv={};

      srv.setValue=function(value){
      this.srv.var = value;
      $rootScope.$broadcast('varChanged');

      }
      return srv;
})

and finally, the 3 controllers for directives.

.controller('MainController',function($scope,ShareDataFct){
            $scope.$watch('varChanged',function(){
            $scope.myvar=ShareDataFct.var;
            })
      })
.controller('Dir1Controller',function($scope){
  //nothing to do here yet
      })
  .controller('Dir2Controller',function($scope){
  //nothing to do here yet
  })

and then I try to change the ShareDataFct var but the view (ng-switch) does not change to show the directives according to the myvar change. Please advise. Thank you.


Solution

  • Actually you have some several problems.

    1st : You're using $rootscope.$broadcast and try to catch the result with a $watch.

    You should use $scope.$on instead of watch.

    2nd : You should never try to use $rootscope, $broadcast and $watch to update vars. If you try to do so, you're doing it wrong.

    How to do it ? Just share the var directly from your factory.

    app.factory('ShareDataFct',function(){
      var srv={};
      srv.data={};
      srv.data.value="";//init your value here
      return srv;
    })
    

    In your controller you can bind it like this :

      .controller('MainController',function($scope,ShareDataFct){
            $scope.data=ShareDataFct.data;
      })
    

    In your view use it like this :

      <div>{{data.value}}</div>
    

    In your ng-switch :

      <div ng-switch on="data.value">
         <div ng-switch-when="Test"> This is a test</div>
         <div ng-switch-when="TestAgain"> This is a test ... again !</div>
      </div>
    

    Notice that it is important to share an object and not a primitive value since updating the value would erase the reference and it wouldn't update in the other part of the application.

    Here is a working plunker as exemple.

    Hope it helped.

    EDIT : Added the plunker