angularjs和谷歌Chrome扩展

时间:2014-05-31 13:00:33

标签: angularjs google-chrome google-chrome-extension angularjs-factory

我有一个simpe google-chrome扩展程序。我正在使用书签,它出现在清单文件中。首先,我在控制器中使用chrome bookmarks api,效果很好。但我决定使用工厂来获得清晰的代码和最佳实践。

我的index.html文件

<!DOCTYPE html>
<html lang="en" ng-app="BookmarksSharer" ng-csp>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>bokmarks sharer</title>
    <link rel="stylesheet" href="/css/main.css"/>
    <script src="/javascript/jquery-2.1.1.min.js"></script>
    <script src="/javascript/angular.min.js"></script>
    <script src="/javascript/bookmark_sharer.js"></script>
    <script src="/javascript/MainController.js"></script>
    <script src="/javascript/BookmarkService.js"></script>
</head>
<body>
    <div id="main_popup" ng-controller="MainController">
        <p>Bookmarks</p>
        <ul>
            <li ng-repeat="bookmark_folder in bookmarks_folders" id="{{bookmark_folder.title}}">
                {{bookmark_folder.title}}
                <ul ng-repeat="bookmarks in bookmark_folder">
                    <li ng-repeat="bookmark in bookmarks | filter">{{bookmark.title}}</li>
                </ul>
            </li>
        </ul>
    </div>
</body>
</html>

bookmark_sharer.js很简单

var app = angular.module("BookmarksSharer", []);

MainController.js也非常简单。

app.controller('MainController',['$scope', 'bookmarkFactory', function($scope, bookmarkFactory){
    $scope.boormarks_folders = bookmarkFactory.folders;
}]);

我的工厂

app.factory('bookmarkFactory', function () {
    var bookmarks_folders;
    function allBookmarksFolders(){
        chrome.bookmarks.getTree(function(bookmarks_tree){
            bookmarks_folders = bookmarks_tree[0].children;
        });

        return bookmarks_folders;
    }

    return {
        folders: allBookmarksFolders()
    };
});

为什么$ scope.bookmarks_folders未定义?

ExpertSystem你的代码也不行。简单的解决方案是

app.controller('MainController',['$scope', function($scope){
    chrome.bookmarks.getTree(function(nodes){
        $scope.bookmarks_folders = nodes[0].children;
        $scope.$apply();
    })
}]);

但我想用工厂或服务组织我的代码。

1 个答案:

答案 0 :(得分:4)

chrome.bookmarks.getTree() 是异步的,因此在getAllBookmarks()函数返回时,bookmarks_folders未定义。

您的服务公开了一个属性folders),该属性绑定到allBookmarksFolders()的结果,唉undefined

由于此操作是异步的,因此您的服务应该返回一个promise,因此控制器可以使用该promise并在返回时获取实际数据:

// The service
app.factory('bookmarkFactory', function ($q) {
    function retrieveAllBookmarksFolders() {
        var deferred = $q.defer();
        chrome.bookmarks.getTree(function (bookmarks_tree) {
            deferred.resolve(bookmarks_tree[0].children);
        });
        return deferred.promise;
    }

    return {
        foldersPromise: retrieveAllBookmarksFolders()
    };
});

// The controller
app.controller('MainController', function($scope, bookmarkFactory){
    bookmarkFactory.foldersPromise.then(function (bookmarks_folders) {
        $scope.boormarks_folders = bookmarks_folders;
    });
});

主要问题来自于(在您的实现中)您在该点返回绑定到bookmarks_folders的值,然后重新分配bookmarks_folders以保存对不同对象的引用( bookmarks_tree[0].children)。

您服务中的事件流程有点像这样:

    声明
  1. bookmarks_folders(并初始化为undefined)。
  2. allBookmarksFolders()已执行并返回(仍未定义)bookmarks_folders
  3. folders被分配了对bookmarks_folders当前引用的对象的引用(即未定义)。
  4. getTree()回调执行并向bookmarks_folders分配对其他对象(bookmarks_tree[0].children)的引用。此时folders对此一无所知,并继续引用前一个值(未定义)。
  5. 另一种方法($resource btw使用的方法)是不为bookmarks_folders分配新引用,而是修改已引用的对象。

    // The service
    app.factory('bookmarkFactory', function () {
        var bookmarks_folders = [];   // initialize to an empty array
        function allBookmarksFolders(){
            chrome.bookmarks.getTree(function(bookmarks_tree){
                // Here we need to modify the object (array)
                // already referenced by `bookmarks_folders`
    
                // Let's empty it first (just in case)
                bookmarks_folders.splice(0, bookmarks_folders.length);
    
                // Let's push the new data
                bookmarks_tree[0].children.forEach(function (child) {
                    bookmarks_folders.push(child);
                });
            });
    
            return bookmarks_folders;
        }
    
        return {
            folders: allBookmarksFolders()
        };
    });