Javascript 带有HTTP请求数据的AngularJs指令
我对AngularJs比较陌生,当数据来自HTTP请求时,我在使用自定义指令时遇到问题 我有一个带有HTTP get请求的服务Javascript 带有HTTP请求数据的AngularJs指令,javascript,html,angularjs,angularjs-directive,Javascript,Html,Angularjs,Angularjs Directive,我对AngularJs比较陌生,当数据来自HTTP请求时,我在使用自定义指令时遇到问题 我有一个带有HTTP get请求的服务 app.service('someService', function($http, $q){ this.getData = function(){ var deferred = $q.defer(); $http({ method: 'GET', url: 'theUrl'
app.service('someService', function($http, $q){
this.getData = function(){
var deferred = $q.defer();
$http({
method: 'GET',
url: 'theUrl'
})
.success(function(data, status){
deferred.resolve(data);
})
.error(function(data, status){
deferred.reject;
})
return deferred.promise;
}
})
以及调用服务的控制器
app.controller('someConroller', function($scope, someService){
someService.getData().then(function(response){
$scope.data = response;
})
$scope.someArrayData = [
{.....}, {.....}, ...
]
}
下面是一个非常简单的自定义指令
app.directive('customDirective', function(){
return {
link: function(scope, element, attrs){
console.log(scope[attrs['customDirective']]);
}
}
})
问题是,当我使用someArrayData
获取指令实例时,它工作正常。但是,当我使用data
(我从http服务获得的数据)console.log(data)获取指令的实例时,会给出未定义的结果
<div custom-directive="someArrayData"></div><!-- console.log(scope[attrs['customDirective']]) gives the expected result -->
<div custom-directive="data"></div><!-- console.log(scope[attrs['customDirective']]) undefined -->
谢谢你的帮助 控制器和指令具有不同的作用域,因此当您在控制器中分配
$scope.data
时,您并不是在为指令执行操作。因此,您应该在指令中插入服务,并在那里请求数据
如果您在理解范围继承人档案方面有困难,请在中详细阅读
我建议下载Chrome的扩展-它允许您检查页面上的所有不同范围。这是因为链接指令时尚未检索数据。 在以下情况下,您可以简单地用ng包装html元素:
<div ng-if="data">
<div custom-directive="data"></div>
</div>
您需要一个
$watch
来“监听”指令中的新值,一旦您的服务解决了这个问题。有多种方法可以做到这一点,但这将是理解概念最直接的方法。另外,如果您将值绑定到该指令范围,您可能会稍微清理一下这一点-实际上,您对范围[attrs[…
的调用可以简化
angular.module('app', [])
.controller('ctrl', function($scope, $timeout) {
// -- simulate ajax call
$timeout(function() {
$scope.data = ['A', 'B', 'C'];
}, 500)
})
.directive('customDirective', function() {
return {
scope: {
data: '=customDirective'
},
link: function(scope, elem, attrs) {
scope.$watch('data', function(newVal, oldValue) {
console.log(newVal) // -- or console.log(scope.data)
});
}
}
});
-demoHTTP响应是否包含您期望的格式的数据?是的,它包含数据。但是{{data}在视图中绑定数据。这是因为视图绑定到控制器-但是指令有一个单独的子范围。尝试它!我会尝试,但是这样做,自定义指令将取决于服务而不是从视图中注入的数据。它是不可重用的。您是对的,它是不可重用的。您可以考虑更改您的设计。如果您想使用控制器中的数据,为什么要制定一个单独的指令?另外,请查看我对Batarang的编辑。非常有用。这不是整个指令。我将其简化,以显示我的问题所在。感谢您的回答,您的解决方案应该有效,但我不知道为什么。@Mohamed Elsaqa提出的解决方案有效。rememb呃,用
=
做出正确的范围声明谢谢你的回答,它工作得很好,我不明白为什么@scniro提出的观察者不起作用。@BillBilal的解决方案工作得很好。他的解决方案是基于观察附加到指令范围的值,每当它被更改时,你可以触发任何逻辑希望