RSKMR RSKMR - 6 months ago 11
AngularJS Question

angularjs directive + apply scope value in many controller

In angularjs when using directive how to apply the scope(isolated scope) value update into many controller.

For example:

I have many templates in view page:


  1. left menu template

  2. top menu template

  3. right content template.



the above things using ui-router plugin.
In this scenario right content have the controller name is ordersController.

Left menu template:

<a ng-custom-click data="data" href="#/order"> Orders </a>


List
.. etc.

app.controller('myapp', function($scope){

$scope.data = {
list : true,
details : false,
test : "rk controller"
};
}


Directive code:

app.directive('ngCustomClick', function() {
return {
restrict : 'A',
replace : false,
controller : 'ordersController',
scope : {
data : '='
},
link : function(scope, el, attrs) {
el.bind('click', function(e) {
scope.data = {
list : false,
details : true,
test : "abcd directive"
};
});
}
};
});


Here ordercontroller is no relationship with left menu template.

So when click the link means the scope.data values need to change in ordercontroller.

Answer

Nope that won't work.

For each directive you're using, a new controller with his own $scope wil be created. So they don't share datas. You need to share them using a service

Here is a working snippet

    var app = angular.module("app",[]);
    app.service('myService', function(){
       this.data = {
                list : true,
                details : false,
                test : "rk controller"
            };
      return this;
    });
    app.controller('myapp2', function($scope, myService){

      $scope.dataOrders = myService.data;
      //optionnal if you want to save change from you order to the service
      $scope.$watch('dataOrders', function(newValue){
          myService.data = newValue;
      });
      // if service's data change resync it
      $scope.$watch(function(){return myService.data;}, function(newValue){
           $scope.dataOrders = newValue;
      });
    }
    );
    app.directive('ngCustomClick', function(myService) {
        return {
            restrict : 'A',
            replace : false,
            scope : {
               
            },
            link : function(scope, el, attrs) {
                el.bind('click', function(e) {
                    myService.data = {
                     list : false,
                     details : true,
                     test : "abcd directive"
                  };
                  scope.$apply();
                });
            }
        };
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app">
      <div>
          <a ng-custom-click href="#/order"> Orders </a> 
     </div>
     <div ng-controller="myapp2">
        Orders : {{dataOrders}} 
      </div>
   </div>