【问题标题】:Updating the data in the angularjs service and controllers更新 angularjs 服务和控制器中的数据
【发布时间】:2014-09-14 01:28:36
【问题描述】:

我有一个名为“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. 导航到另一个州。

我尝试了下面的代码,但没有像我预期的那样工作:

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

有没有更好的方法来做到这一点?

【问题讨论】:

  • 如果您导航到另一个状态,它会自动加载该新状态的 Ctrl 和模板?您面临什么问题?
  • 它不会那样做。它将旧数据保留在服务中。

标签: javascript angularjs angularjs-service angularjs-routing


【解决方案1】:

好的,我只需要这样做:

$rootScope.$apply();

【讨论】:

    猜你喜欢
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多