从$http请求角度中引用$scope变量
Reference $scope variables from within $http request angular
我对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);
});
});
使用$q
和promises
感谢@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;
});
});
相关文章:
- 引用对象中的通用值
- 如何在JavaScript中将字符串转换为函数引用
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- AngularJS:ng之后,重复$scope值未按预期更新
- 在动态创建的元素上获取对特定选择器的引用
- 强制DOM在$scope模型对工厂模型的引用发生更改时进行渲染
- 未捕获的引用错误:未定义$scope - AngularJS
- 通过引用传递$scope变量以函数
- AngularJS将字符串转换为引用$scope中的对象的对象/数组
- JavaScript Scope:引用任意新对象的计时器
- 从$http请求角度中引用$scope变量
- 获取$rootScope事件处理程序的$scope引用
- 在没有$scope的指令中引用作用域变量
- & # 39;这个# 39;真正的引用"$scope"在AngularJS'
- 在angularjs中的$scope成员函数中引用函数中的变量
- 无法在AngularJS的$scope中引用类成员(Array)
- 将指向服务对象属性的指针/引用添加到$scope变量
- AngularJS-为什么$scope.properties's的值在更改引用它的变量时发生更改
- 在$scope中丢失此引用$在活动中
- 使用 vm 而不是 $scope 引用指令属性