angularjs – 控制器内部指令的行为

前端之家收集整理的这篇文章主要介绍了angularjs – 控制器内部指令的行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道控制器的$范围可以被分配给指令中的链接函数

例如,在这段代码中,我可以从声明的控制器调用一个函数,在浏览器控制台上打印“Hello World”

.directive('myDirective',[function () {
        return {
            restrict : 'E',replace : true,controller: 'MyController',templateUrl : 'directives/myDirective.tpl.html',link : function (scope,elem,attrs,controller) {
                scope.message = 'Hello World!';
            }
        };
    }])

    .controller('MyController',[function ($scope,$element,$attrs,$log,$timeout) {

        // $timeout to wait the link function to be ready.
        $timeout(function () {
            // This prints Hello World as expected.
            $log.debug($scope.message);
         });


        });
    }])

好的,这很好。

我的问题是:

>在这种方法中,控制器和指令之间将共享相同的范围?
>使用这种方法有什么后果?让我们假设我不会在控制器中操纵DOM元素,只能在链接函数中操作。
>我真的需要避免操纵这个控制器中的DOM元素?即使$范围,$ elem等是一样的?

这些是我在Angular Directive documentation没找到的问题。

Here’s a plunker with the sample code

In this approach,it is the SAME scope that will shared between the controller and the directive?

是的。

What is the consequences to use this approach? Let us assume that I will not manipulate DOM elements in controller,only in link function.

控制器是提供指令的行为,就像常规Angular应用程序一样。也就是说,您应该仅操纵控制器功能中的范围。如果您需要从链接功能更改范围,请调用它的方法。此外,由于控制器在链接功能之前执行,所以您应该在前者中初始化范围,以便后者可以获得有效的模型。

I really need to avoid manipulate DOM elements in this controller? Even if the $scope,$elem,etc are the same?

根据定义,链接函数是执行DOM操作的地方。我找不到阻止你操纵指令控制器内的DOM的技术原因,除了你不应该。事实上,为了检查我刚刚修改了一个我已经编写的指令,并将链接功能中的所有代码移动到控制器功能,并且一切都保持工作。但是,如果将范围逻辑和DOM操作混合在一起,我认为很难跟踪发生了什么。

最后,你可能会发现这篇文章很有用:Understanding Directives

原文链接:https://www.f2er.com/angularjs/144303.html

猜你在找的Angularjs相关文章