小编sos*_*gon的帖子

$使用AngularJS观察服务变量或$广播事件

我正在使用服务在控制器之间共享数据.应用程序必须在修改变量时更新DOM.我找到了两种方法,你可以在这里看到代码:

http://jsfiddle.net/sosegon/9x4N3/7/

myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope, myService ){
    $scope.init = function(){
        $scope.myVariable = myService.myVariable;
    };
}]);
Run Code Online (Sandbox Code Playgroud)

myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){
    $scope.increaseVal = function(){
        var a = myService.myVariable.value;
        myService.myVariable.value = a + 1;
    };
}]);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/sosegon/Y93Wn/3/

myApp.controller( "ctrl1", [ "$scope", "myService", function( $scope, myService ){
    $scope.init = function(){
        $scope.increasedCounter = 1;
        $scope.myVariable = myService.myVariable;
    };
    $scope.$on( "increased", function(){
        $scope.increasedCounter += 1;
    }
}]);
Run Code Online (Sandbox Code Playgroud)

myApp.controller( "ctrl2", [ "$scope", "myService", function( $scope, myService ){
    $scope.increaseVal …
Run Code Online (Sandbox Code Playgroud)

broadcast watch angularjs

6
推荐指数
1
解决办法
9982
查看次数

标签 统计

angularjs ×1

broadcast ×1

watch ×1