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/
他們是不是使用不同的範圍? – Shomz
使用角度服務而不是工廠可以更好地實現 – V31