質問

I have a message service that stores any messages that need to be displayed to the user like this

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

what do I need to do in my controller to be able to ng-repeat the content of messages and have it update whenever another controller adds a message?

役に立ちましたか?

解決

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;
        }
    };
);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top