Question

I have a controllers with name PostController and CommentController
PostController having the function showPost
CommentController having the function showComment
i want to execute the both the functions when button is clicked

<button href="#" ng-click="showPost();showComment()" class="btn">show</button>

how can i do that one without specifying the nested controller concept

Was it helpful?

Solution

You can achieve this by using service/factory. Here is simple example how it should work:

JS

var myApp = angular.module('myApp', []);

function CommentController($scope,  myStorage) {   
    $scope.myStorage = myStorage;

    $scope.showMe = function(){
      myStorage.setIndex(3);
    }
}

function PostController($scope,  myStorage) {   
    $scope.myStorage = myStorage;    
}


myApp.factory('myStorage', function () {

       var currentBusinessIndex = 0;

       return {
            getIndex: function () {                
               return currentBusinessIndex;
            },
           setIndex: function (index) {
               currentBusinessIndex = index;               
            }
        }
  });

HTML

<div ng-controller="CommentController">
    <button ng-click="showMe();">press  me</button>
    <pre>{{myStorage.getIndex()}}</pre>
</div>

<div ng-controller="PostController">
    <pre>{{myStorage.getIndex()}}</pre>
</div>

Demo Fiddle

In addition, you can watch the service data by using $watch, to trigger on any data change

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top