服务更新中的数据更新ng-repeat

时间:2014-03-18 20:31:19

标签: angularjs angularjs-ng-repeat angularjs-service

我有一个消息服务,可以存储需要像这样显示给用户的任何消息

app.controller('messageCtrl', function($scope, messages){
    //what to do
});

app.factory('messages', function(){
    return {
        messages: [
            {type:'info', text: 'info Message'},
            {type:'success', text: 'success Message'},
            {type:'warning', text: 'warning Message'},
            {type:'danger', text: 'danger Message'}
        ],

        addMessage: function(message){
            messages.push(message);
        },

        getMessages: function(){
            return messages;
        }
    };
);

我需要在我的控制器中做些什么来重复消息内容并在其他控制器添加消息时更新消息?

1 个答案:

答案 0 :(得分:0)

app.controller('messageCtrl', function($scope, messages){
    $scope.localMessages = messages.messages;
    //Just be sure to not replace the original array and this will work
    //if you need to repopulate the array or empty it use angular.copy()
});

app.factory('messages', function(){
    return {
        messages: [
            {type:'info', text: 'info Message'},
            {type:'success', text: 'success Message'},
            {type:'warning', text: 'warning Message'},
            {type:'danger', text: 'danger Message'}
        ],

    addMessage: function(message){
        messages.push(message);
    },

    getMessages: function(){
        return messages;
        }
    };
);