【问题标题】:Reference $scope variables from within $http request angular从 $http 请求角度中引用 $scope 变量
【发布时间】:2014-11-13 22:12:41
【问题描述】:

我对 angularjs 很陌生,很难弄清楚这个问题。

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

例如:我们在控制器中定义了 $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 访问 /use {{name}}?

【问题讨论】:

  • 将其作为参数传递给getSnapshotAccount.getSnapshot($scope.name).success(function(data) {});

标签: javascript angularjs


【解决方案1】:

您需要使用内部 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);
    });
});

【讨论】:

  • 这似乎是答案!但是,我正在处理一个关于从 json 脚本返回的信息的数组。每个数组元素都有一些需要使用 $interpolate 函数的索引。这是可以应用于整个数组的东西吗?
  • 您必须分别插入每个字符串。我认为您不能将其应用于整个数组。
【解决方案2】:

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

Here's a plunker.

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

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2017-02-02
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多