AngularJS:来自http调用的模型数据在指令中不可用
似乎存在一个bug,从http调用获取的模型数据存在于$scope中,但不存在于指令中。下面是说明问题的代码: Jsfiddle:AngularJS:来自http调用的模型数据在指令中不可用,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,似乎存在一个bug,从http调用获取的模型数据存在于$scope中,但不存在于指令中。下面是说明问题的代码: Jsfiddle: var myApp=angular.module('myApp',[])指令('prettyTag',函数($interpolate){ 返回{ 限制:'E', 链接:函数(范围、元素、属性){ var text=element.text(); //var text=attrs.ngModel; 变量e=$interpolate(文本)(范围); var htmlT
var myApp=angular.module('myApp',[])指令('prettyTag',函数($interpolate){
返回{
限制:'E',
链接:函数(范围、元素、属性){
var text=element.text();
//var text=attrs.ngModel;
变量e=$interpolate(文本)(范围);
var htmlText=“+e+”;
html(htmlText);
}
};
});
函数MyCtrl($scope、$http、$templateCache){
$scope.method='JSONP';
$scope.url='1http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';
$scope.fetch=函数(){
$scope.code=null;
$scope.response=null;
$http({
方法:$scope.method,
url:$scope.url,
缓存:$templateCache
}).
成功(功能(数据、状态){
$scope.status=状态;
$scope.data=数据;
}).
错误(功能(数据、状态){
$scope.data=data | |“请求失败”;
$scope.status=状态;
});
};
}
HTML
<div ng-controller="MyCtrl">
<h1>Angular $http call / directive bug</h1>
<p>This fiddle illustrates a bug that shows that model w/ data fetched via an http call
is not present within a directive.</p>
<hr>
<h2>HTTP call settings</h2>
<li>Method: {{method}}
<li>URL: {{url}}
<br>
<button ng-click="fetch()">fetch</button>
<hr/>
<h3>HTTP call result</h3>
<li>HTTP response status: {{status}}</li>
<li>HTTP response data: {{data}}</li>
<hr/>
<h2>Pretty tag</h2>
<pretty-tag>make this pretty</pretty-tag>
<hr/>
<h3 style="color: red" >Should show http response data within pretty tag</h3>
[<pretty-tag>{{data}}</pretty-tag>] // <=== this is empty
</div>
$http调用/指令错误
这把小提琴演示了一个bug,它显示了通过http调用获取的模型w/数据
指令中不存在
HTTP呼叫设置
方法:{{Method}}
URL:{{URL}}
取来
HTTP调用结果
HTTP响应状态:{{status}
HTTP响应数据:{{data}
漂亮的标签
把它弄漂亮
应该在pretty标记中显示http响应数据
[{{data}}]/您正在指令实现中替换指令的内容。由于$http请求是异步的,因此该指令在检索数据并将其分配给作用域之前完成
在指令内的data
变量上放置一个手表,然后重新呈现内容,如
scope.$watch(attrs.source,function(value) {
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
});
scope.$watch(属性源、函数(值){
变量e=$interpolate(文本)(范围);
var htmlText=“+e+”;
html(htmlText);
});
根据@Marks的反馈和您的请求,我已经更新了fiddle
至少这是可行的。谢谢这也使得指令被锁定以监视$scope.data变量。有没有办法不这样做?@supercbra,{{data}
,然后观察该属性:scope.$watch(attrs.attr1,function(value){…})
这告诉我所有指令都应该有一个内置的观察机制,因为它们的数据可能来自http调用…只要您保持对数据对象的引用,清除并填充它,而不是替换参考,这只手表会工作。
scope.$watch(attrs.source,function(value) {
var e = $interpolate(text)(scope);
var htmlText = "<b>" + e + "</b>";
element.html(htmlText);
});