我的主页上有以下代码
<ul>
<li ng-repeat="item in list" ng-bind-html-unsafe="item.Content" ng-include="item.Template" > </li>
</ul>
item.template的值是 template1 ,item也有一个属性为item.WebServicePath,其值为
"http://.../....htm"
和template1有: -
<directive1 s-web-service-path="{{item.WebServicePath}}" >
</directive1 >
我的指示1: -
directive("directive1", function ($http) {
try {
return {
restrict: "E",
transclude: true,
scope: {
sWebServicePath: "@"
},
template: "<div> {{sWebServicePath}}</div>", -- this gets rendered with expected value
link: function (scope, element, attrs) {
var request = {};
$http({ method: "POST", url: attrs.sWebServicePath, data: request }).
success(function (data, status) {
scope.response = data;
}).
error(function (data, status) {
alert("Service Call Error");
})
}
}
}
catch (e) {
alert(e);
}
});
但是 attrs.sWebServicePath 被认为是未定义的这种情况,我已经看到了egghead视频,这与他做的完全相同,唯一的区别是item.sWebServicePath是在$ scope中定义的但在我的情况下,项是在ng-repeat迭代期间生成的,所以这必然会失败吗?但在指令模板中,我使用绑定即{{}}我得到正确的值,为什么我不能通过attrs访问它?
答案 0 :(得分:0)
在调用链接函数时尚未分配sWebServicePath
的动态值。
在$ watch中包裹$ http。
directive("directive1", function ($http) {
try {
return {
restrict: "E",
transclude: true,
scope: {
sWebServicePath: "@"
},
template: "<div> {{sWebServicePath}}</div>", -- this gets rendered with expected value
link: function (scope, element, attrs) {
var request = {};
scope.$watch('sWebServicePath', function(newVal) {
if (newVal) {
$http({ method: "POST", url: newVal, data: request }).
success(function (data, status) {
scope.response = data;
}).
error(function (data, status) {
alert("Service Call Error");
})
});
}
}
}
}
catch (e) {
alert(e);
}
});