本文介绍了内部指令控制器的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,一个 $范围控制器中可以共享一个链接功能指令

例如,在此code我可以宣布控制器调用一个函数来打印的'Hello World浏览器控制台上:

  .directive('myDirective',[功能(){
        返回{
            限制:'E',
            更换:真实,
            控制器:'myController的,
            templateUrl:指令/ myDirective.tpl.html',
            链接:功能(范围,ELEM,ATTRS,控制器){
                scope.message =世界,你好!;
            }
        };
    }])    .controller('myController的',[功能($范围,$元,$ ATTRS,$​​日志$超时){        // $超时等待链接功能做好准备。
        $超时(函数(){
            //这个打印Hello World预期。
            $ log.debug($ scope.message);
         });
        });
    }])

好吧,这工作正常。

我的问题是


  1. 在这种方法中,它是在将在控制器和指令?
  2. 之间的共享范围
  3. 什么是使用这种方法的后果是什么?让我们假设我会的不可以操纵控制器 DOM 元素只有在链接功能

  4. 我真的需要避免操作DOM元素在这个控制器?即使 $范围 $ ELEM 等都是一样的吗?

这些都是我没有在发现的问题。

一个plunker。


解决方案

Yes, it is.

The controller is what provides the directive's behavior, just like with a regular Angular application. That said, you should manipulate the scope inside the controller function only. If you need to change the scope from the link function, call a method of it. Besides, since the controller is executed before the link function, you should initialized the scope in the former so the latter can get a valid model to work on.

By definition, the link function is the place to perform DOM manipulation. I can't find a technical reason that would prevent you from manipulating the DOM inside the directive's controller except that you shouldn't. In fact, in order to check that I've just changed one directive I've written and moved all the code from the link function to the controller function and everything's kept working. But if you mix both scope logic and DOM manipulation together I think it'll be hard to track down what's going on.

Finally, you may find this article useful: Understanding Directives.

这篇关于内部指令控制器的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 02:39
查看更多