在angular指令中更改父范围变量,其中parent具有隔离范围

时间:2016-10-19 13:31:43

标签: 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

                    }


                }

我可以看到客户在dev控制台的$ parent范围内得到更新,但视图显示{{customer}}而不是输出客户。

1 个答案:

答案 0 :(得分:0)

You should use scope.$apply after $compile.

See this answer: Why call scope.$digest() after $compile(element)(scope) in unit testing


UPDATE

Another culprit might be priority - angular docs. You should set the priority of the key directive higher than some-directive so that user data is available when link function of some-directive is executing.


UPDATE 2

I think you should do what you want (call the factory based on key) in the controller of the directive. Please see this plunker: https://plnkr.co/edit/BH3bDD?p=preview.