$watch a service variable or $broadcast an event with AngularJS

橙三吉。 提交于 2019-12-04 06:55:57
Jesus Rodriguez

Your code is over complex. I am not sure what are you trying to do with that directive.

You don't have to $watch nor $broadcast anything.

You have a object in your service which has a primitive. In ctrl1 you're assigning the object to the $scope (That is good, because if we assign it to the primitive, it will need a $watch for sure as seen here.

So far so good. To increase the value, there is an easy way just doing myVal++ no need of temporary variables.

For the directive, I am not sure what's your goal here, I simplified it to what you need to put that example to work. You don't need to $watch nor $broadcast. ctrl1 is aware of the changes made to myVariable object so if it changes, you will notice it.

Code:

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

myApp.provider( "myService", function(){

    var myVariable = {
        value: 0
    };
    this.$get = function(){
        return {
            myVariable: myVariable,
            increase: function() {
                myVariable.value++;
            }
        };
    };
});

myApp.directive( "dir1", function(){
    return {
        restrict: 'EA',
        template: '<div>value: {{myVariable.value}}</div>',
        replace: true
    };
});


myApp.controller("ctrl1", ["$scope", "myService", function($scope, myService){
    $scope.myVariable = myService.myVariable;
}]);

myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){
    $scope.increaseVal = myService.increase;
}]);

View:

<body ng-app = "myApp">
    <div dir1="myVariable.value" ng-controller = "ctrl1">
    </div>

    <div ng-controller = "ctrl2">
        <button ng-click = "increaseVal()">
            Increase
        </button>
    </div>


</body>

Here is my forked fiddle: http://jsfiddle.net/uWdUJ/ Same idea a little bit cleaned.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!