我有一个指令内的数据绑定(bind)问题,该指令调用另一个指令。
这是主要指令:
var app = angular.module('app');
app.directive("myMainDirective", function ($http) {
return {
scope: {
paramId: '='
},
link: function (scope) {
$http.get('some/url/' + scope.paramId+ '.json'
).success(function (data) {
scope.idFromServer = data;
});
},
template: '<span other-directive id="idFromServer"></span>'
}
});
这是另一个指令:
var app = angular.module('app');
app.directive("otherDirective", ['$http', function(http) {
return {
template: "<span>{{name}}</span>",
scope: {
id: "="
},
link: function(scope) {
http.get('another/url/' + scope.id + '.json').then(function(result) {
scope.name = result.data.name;
}, function(err) {
scope.name = "unknown";
});
}
}
}])
以及调用主指令的 html 代码:
<span my-main-directive param-id="myObject.id"></span>
当调用“other-directive”时,“idFromServer”没有绑定(bind),是“undefined”,所以显示为“undefined”。
我可能遗漏了一些愚蠢的东西,但我不明白是什么...... (我的代码可能不是最好的,我是 angularjs 的新手,特别是指令,我尝试了很多方法来完成我想要的。)
最佳答案
根据我的评论,这是一种可能有效的方法,使用范围。$watch:
scope.$watch('id', function(id) {
$http.get('some/url/' + id + '.json')
.success(function (data) {
scope.idFromServer = data;
});
};
这将进入嵌套指令的链接函数。
关于javascript - Angular JS - 指令中的数据绑定(bind)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707603/