我有以下指令:
<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) {
}
};
我有另一个基于 key 的指令...一旦获取客户,我添加一个属性,设置客户的结果并重新编译。它不起作用
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}} 而不是输出客户。
最佳答案
您应该在 $compile
之后使用 scope.$apply
。
查看这个答案:Why call scope.$digest() after $compile(element)(scope) in unit testing
<小时/>更新
另一个罪魁祸首可能是优先级
- 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/