문제

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

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top