1

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.

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

});

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.

I really don't understand why.

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!

4

1 回答 1

1

$scope.$apply()OP 通过在回调的末尾添加解决了这个问题(见上面的评论) :

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

对任何登陆此页面并遇到类似问题的人的简短解释:

来自关于“范围”的 AngularJS 文档(更具体地说,来自标题为“范围生命周期”的部分):

模型突变

为了正确观察突变,您应该只在 scope.$apply() 内进行突变。(Angular API 隐式执行此操作,因此在控制器中进行同步工作或使用 $http 或 $timeout 服务进行异步工作时不需要额外的 $apply 调用。


另请参阅这个简短的演示

于 2013-10-31T13:56:09.350 回答