javascript - 在父级具有隔离范围的 Angular Directive(指令)上更改父级范围变量

标签 javascript angularjs

我有以下指令:

<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/

相关文章:

javascript - orderBy通过带下拉列表的嵌套排序将数据分组

Javascript:有些东西太简单而无法与外部链接?

javascript - 不同的ng-switch动画

javascript - jQuery函数,用于检查是否排序了多个div的数据索引

javascript - jQuery检查输入是否是类型复选框?

javascript - 在多个层面上提高 AngularJS 的性能

javascript - Angular js中另一个ng-app的调用方法

javascript - 一起使用 jQuery 和 AngularJS?

c# - 为什么我不能将此 json 转换为 c#

javascript - 如何用多个 api 调用填充数组?