从$http请求角度中引用$scope变量

Reference $scope variables from within $http request angular

本文关键字:引用 scope 变量 http 请求      更新时间:2023-09-26

我对angularjs很陌生,很难解决这个问题。

基本上,我们使用工厂为我们的应用程序请求数据。当工厂返回承诺时,我们希望在我们的范围内定义的返回承诺中的数据能够被使用,但它只是作为页面上的文本返回。

例如:我们在控制器中定义了 $scope.name:

app.controller('AccountController',function($scope,Account) {
    $scope.name = 'Abby';
    $scope.news = [];
    Account.getSnapshot().success(function(data) {
        $scope.news.push(data);
    });
});

因此,工厂(getSnapshot)将从$http请求中返回类似"Hello {{name}}"的内容,如下所示:

app.factory('Account',function($http) {
    return {
        getSnapshot : function() { 
            return $http.get('data.php'); 
        }
    }
});

是否可以允许工厂从$scope访问/使用 {{name}}?

您需要

使用内部 Angular $interpolate服务:

app.controller('AccountController', function($scope, $interpolate, Account) {
    $scope.name = 'Abby';
    $scope.news = [];
    Account.getSnapshot().success(function(data) {
        var text = $interpolate(data)($scope);
        $scope.news.push(text);
    });
});

使用$qpromises感谢@dfsq在我的帖子中与此类似的回答。完美工作。

这是一个笨蛋。

// Factory method.
app.factory('Account', function($http, $q) {
    var data;
    return {
        getSnapshot: function() {
            return data ? $q.when(data) : $http.get('data.json').then(function(response) {
                data = response.data;
                return data;
            })
        }
    }
});
// Controller method.
app.controller('AccountController', function($scope, Account) {
    $scope.name = 'Abby';
    $scope.news = [];
    Account.getSnapshot().then(function(data) {
        $scope.news = data;
    });
});