我有以下指令:
<some-directive key="123"></some-directive>
在指令中:
angular.module('app').directive('someDirective', ['someFactory', '$compile', '$timeout', function(PatientFactory, $compile, $timeout){
return {
scope:{
customer: "="
},
controller: _controller,
templateUrl: 'components/sometemplate.html',
link: function (scope, element, attrs) {
}
};
我有另一个基于键的指令......一旦获取客户,我添加一个属性,使用结果设置客户并重新编译。它不工作
angular.module('app').directive('key', ['someFactory', '$compile', '$timeout', function(PatientFactory, $compile, $timeout){
return{
link: function(scope, el, attr){
//if key provided from, we need to get the customer based on this key.
if (attr.key) {
scope.someFactory.getCustomerByKey(attr.key).then(function (res) {
el.attr('customer', res);
var fn = $compile(el);
return function(scope){
fn(scope);
};
});
}else{
//error
}
}
我可以看到客户在开发控制台的 $parent 范围内得到更新,但 View 显示的是 {{customer}} 而不是输出客户。
最佳答案
您应该使用 scope.$apply
在 $compile
之后.
看到这个答案:Why call scope.$digest() after $compile(element)(scope) in unit testing
更新
另一个罪魁祸首可能是 priority
- angular docs .您应该设置 key
的优先级指令高于 some-directive
以便some-directive
的链接功能时用户数据可用正在执行。
更新 2
我认为你应该在指令的 Controller 中做你想做的事情(根据 key 调用工厂)。请看这个插件:https://plnkr.co/edit/BH3bDD?p=preview .
关于javascript - 在父级具有隔离范围的 Angular Directive(指令)上更改父级范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40132862/