AngularJS - 控制器功能顺序 - 一些参考文献不起作用

时间:2016-10-19 14:54:59

标签: javascript angularjs

我有以下代码:titledbApp.controller('TitleListController', ['$cookieStore', function($scope, $http, $cookieStore) {

赢得工作 - 它基本上无法检测$ CookieStore并说它undefined所以所有.get和.put请求都会失败。

当我将$cookieStore中的function()移至开始时($scope之前),它可以正常工作,但$scope$http无法正常工作。

完整代码:

titledbApp.controller('TitleListController', ['$cookieStore', function($cookieStore, $scope, $http) {
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
        $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };
}]);

2 个答案:

答案 0 :(得分:1)

titledbApp.controller('TitleListController', ['$cookieStore', function($cookieStore, $scope, $http)

应该是

titledbApp.controller('TitleListController', ['$cookieStore', '$scope', '$http', function($cookieStore, $scope, $http)

您必须先将它们全部注入,然后才能在代码中访问它们。

答案 1 :(得分:0)

根据angular js官方文档,依赖项的顺序和参数no:应该相同。

titledbApp.controller('TitleListController', ['$cookieStore','$scope', '$http', function($cookieStore, $scope, $http) {
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
            $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };
}]);

您还可以使用函数语法

titledbApp.controller('TitleListController', TitleListController);

function TitleListController($cookieStore,$scope, $http){
    $cookieStore.put('ETag', 'test');
    var etag = 't';
    $http.get('https://api.github.com/users/ImReallyShiny/repos', {headers: {'If-None-Match': 't'}}).then(function successCallback(response, headers) {
            $cookieStore.put('ETag', headers('ETag'));
        $scope.titles = response.data;
        $scope.titles.splice(1, 1);
        $scope.titles.sort(function(a, b){
            if(a.name.toUpperCase() < b.name.toUpperCase()) return -1;
            if(a.name.toUpperCase() > b.name.toUpperCase()) return 1;
            return 0;
        });
        }), function errorCallback() {
        return "Error";
        };

}
相关问题