Angularjs:为什么我需要让我的视图更新上的一个按钮点击? [英] Angularjs : Why I need to click on a button to get my view updated?

查看:151
本文介绍了Angularjs:为什么我需要让我的视图更新上的一个按钮点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想developpe一个Chrome扩展与angularjs,我有一个奇怪的现象,当我尝试用活动标签的URL来初始化$范围。

I'm trying to developpe a chrome extension with angularjs and I have a strange behaviour when I try to initialize the $scope with the url of the active tab.

下面我控制器code:

Here the code of my controller:

var app = angular.module('app', ['app.service']);

app.controller('ItemCtrl', function ($scope, chromeHelper) {

    $scope.website = "No result!";

    // Does not work until I click on something :-/
    chromeHelper.getActiveTabDomain(function (domain) {$scope.website = domain; });

});

所以,当我尝试直接初始化$ scope.website成员没有成功,但是当我点击按钮aftewards $ scope.website然后更新。

So when I try to initialize directly the $scope.website member it doesn't succeed but when I click on the button aftewards $scope.website then updates.

我真的不明白为什么。

下面是我Chromehelper服务的code:

Here is the code of my Chromehelper service:

var service = angular.module('app.service', []);

service.factory('chromeHelper', function() {
    var chromeHelper = {};

    chromeHelper.getActiveTabDomain = function (callback){
            chrome.tabs.query({'active': true}, function(tabs){
                if(tabs && tabs.length > 0) callback(getDomainFrom(tabs[0].url));
            });
        };

    return chromeHelper;
});

function getDomainFrom(url) {
    return url.match(/:\/\/(.[^/]+)/)[1];
}

非常感谢你提前!

Thank you very much in advance!

推荐答案

OP的解决了这个问题(见注释以上)加入 $范围。$适用()在回调的末尾:

The OP solved the problem (see comment above) by adding $scope.$apply() at the end of the callback:

// Does not work until I click on something :-/
chromeHelper.getActiveTabDomain(function(domain) {
    $scope.website = domain;
    $scope.$apply();    // <-- adding this line did the trick
});


任何人登陆这个页面上有类似问题的简短说明:


A short explanation for anyone landing on this page with a similar problem:

从对范围中的 AngularJS文档 (更具体从标题为 范围生命周期 ')

From the AngularJS docs on 'scope' (more specifically from the section titled 'Scope Life Cycle'):

型号突变

为了正确观察突变,你应该只范围内使它们。$适用()。 (角的API做到这一点含蓄,所以不需要额外的$应用呼叫控制器做同步工作的时候,或异步工作$ http或$超时服务。

For mutations to be properly observed, you should make them only within the scope.$apply(). (Angular APIs do this implicitly, so no extra $apply call is needed when doing synchronous work in controllers, or asynchronous work with $http or $timeout services.

又见这个 短演示


See, also, this short demo.

这篇关于Angularjs:为什么我需要让我的视图更新上的一个按钮点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆