更新angularjs服务和控制器中的数据

时间:2014-07-23 02:07:39

标签: javascript angularjs angularjs-service angularjs-routing

我有一个名为' NoteBooksService':

的角度服务
app.factory('NoteBooksService', function() {

    var permanentStorage = window.localStorage;
    // Initializing the local storage if no data exists in the local storage.
    if (permanentStorage.getItem("noteBooks") === null) {
        permanentStorage["noteBooks"] = JSON.stringify([
            {
                name:"Your first notebook", //the defualt title of the notebook
                icon:0, // the defualt icon of the nptebook
                color:"Blue", // the default color of the notebook.
                pages:[ // adding one test page to the notebook.
                    {
                        name:"Your first page",
                        content:"The content of your first page ..."
                    }
                ]
            }
        ]);
    }

    var noteBooks = JSON.parse(permanentStorage["noteBooks"]); // loading the notebooks from local storage.
    return { // providing access to this service
        noteBooks: noteBooks, // used to get all the notebooks
        getNoteBook : function(index) { // returns one particular notebook by index.
            return noteBooks[index]
        }
    }
});

它检查本地存储是否包含密钥,如果不是,则将密钥添加到本地存储。如果本地存储具有密钥,则从本地存储加载数据。

我希望在本地存储中的数据发生更改时更新服务,并且我还想更新控制器中由此服务初始化的变量。

到目前为止,我在每次更改本地存储后使用$window.location.reload();重新渲染整个页面,但现在我需要做两件事。

  1. 重新渲染整个页面
  2. 导航到另一个州。
  3. 我尝试了下面的代码,但它没有像我预期的那样工作:

    $state.go('NoteBook');
    $window.location.reload();
    

    有没有更好的方法呢?

1 个答案:

答案 0 :(得分:0)

好的,我只需要这样做:

$rootScope.$apply();