angularjs factory添加/删除消息

时间:2014-02-18 07:18:02

标签: angularjs factory

为什么我的代码不起作用?

<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)
        }
    }

});

控制器A在工厂“通知”消息中添加一段时间后应退出的消息,它将在出厂时被删除,但不会出现在controllerB更改中。 示例:http://jsfiddle.net/vivalaakam/vL8PC/4/

1 个答案:

答案 0 :(得分: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);
            }
        };
    }
]);