[英]Angular JS - Data binding in directive is not working
我在指令中有一个数据绑定问题,它调用另一个指令。
这是主要指令:
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”不绑定,并且是“未定义”,因此它会导致显示“未定义”。
我可能错过了一些愚蠢的东西,但我看不出是什么......(我的代码很可能不是最好的,我对angularjs很新,特别是指令,我尝试了很多方法实现我想要的。)
根据我的评论,这是使用范围可能有效的一种方式。$ watch:
scope.$watch('id', function(id) {
$http.get('some/url/' + id + '.json')
.success(function (data) {
scope.idFromServer = data;
});
};
这将进入嵌套指令的link函数内部。
我建议的方法之一就是不要在idFromServer
变量上使用双向( =
)绑定,使用{{idFromServer}}
插值指令为属性赋值,然后使用$attr.$observe
它会在插值时调用被评估。
myMainDirective
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>'
}
});
otherDirective
app.directive("otherDirective", ['$http', function(http) {
return {
template: "<span>{{name}}</span>",
scope: true, //isolated scope
link: function(scope, element, attr) {
attr.$observe(attr.id, function(newVal) {
http.get('another/url/' + newVal + '.json').then(function(result) {
scope.name = result.data.name;
}, function(err) {
scope.name = "unknown";
});
});
}
}
}])
由于javascript是异步的,因此两个ajax请求基本上同时运行,并且当other-directive
的请求运行时, id
undefined
。
如果您想尝试测试,只需为idFromServer
设置默认值。 other-directive
的请求将以默认值运行。
编辑:回应你的评论,这是一个非常广泛的问题,有很多解决方案。 我能给你的最好答案就是,从来没有在你的链接函数中运行任何逻辑,只需定义指令的行为和属性 - 这就是链接函数的用途。 模板立即使用,您无法更改。
在这种情况下,您可以获取在父作用域中准备的数据并在属性中传递数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.