2014-02-18 62 views
0

爲什麼我的代碼無法正常工作?angularjs工廠添加/刪除郵件

<div data-ng-app="app" class="container"> 
    <div> 
     <div data-ng-controller="ControllerA"></div> 
     <div data-ng-controller="ControllerB"> 
      <ul> 
       <li data-ng-repeat="notify in notifications">{{notify}}</li> 
      </ul> 
     </div> 

    </div> 
</div> 
<script> 
var app = angular.module('app', []); 
app.controller('ControllerA', ['$scope', 'Notification' , function ($scope, Notification) { 
    var i = 0; 
    Notification.set('Notification ' + i++); 
    setTimeout(function() { 
     $scope.$apply(function() { 
      Notification.set('Notification ' + i++) 
     }) 

    }, 2000) 
}]); 

app.controller('ControllerB', ['$scope' , 'Notification', function ($scope, Notification) { 
    $scope.notifications = Notification.notifications 
    $scope.$watch('notifications', function() { 
     console.log($scope.notifications) 
    }) 
}]); 

app.factory('Notification', function() { 
    var notifications = []; 

    return { 
     notifications: notifications, 
     set: function (name) { 
      notifications.push(name); 
      setTimeout(function() { 
       notifications.shift(); 
       console.log(notifications) 
      }, 5000) 
      console.log(notifications) 
     } 
    } 

}); 

一個controllerA添加在工廠「通知」消息後的一段時間應該退休,它是在工廠中刪除,但不會出現在controllerB變化。
示例:http://jsfiddle.net/vivalaakam/vL8PC/4/

+0

他們是不是使用不同的範圍? – Shomz

+0

使用角度服務而不是工廠可以更好地實現 – V31

回答

0

嘗試使用$ timeout服務而不是setTimeout。

此外,調用$ scope。$ apply基本上是不必要的。

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

app.controller('ControllerA', ['$scope', '$timeout', 'Notification', 
    function ($scope, $timeout, Notification) { 
     var i = 0; 
     Notification.set('Notification ' + i++); 
     $timeout(function() { 
      Notification.set('Notification ' + i++) 
     }, 2000); 
    } 
]); 

app.controller('ControllerB', ['$scope', 'Notification', 
    function ($scope, Notification) { 
     $scope.notifications = Notification.notifications; 
     $scope.$watch('notifications', function() { 
      console.log($scope.notifications); 
     }) 
    } 
]); 

app.factory('Notification', ['$timeout', 
    function ($timeout) {       
     var notifications = []; 
     return { 
      notifications: notifications, 
      set: function (name) { 
       notifications.push(name); 
       $timeout(function() { 
        notifications.shift(); 
        console.log(notifications); 
       }, 5000) 
       console.log(notifications); 
      } 
     }; 
    } 
]);