在自定义指令,并`controller`有什么功能了`link`? [英] In a custom directive, what functionality does `controller` have over `link`?

查看:209
本文介绍了在自定义指令,并`controller`有什么功能了`link`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在试图让创造我自己的AngularJS指令把握,我有做的一切我需要一个例子,但认识到,在从各种例子借款,我现在可以同时在创建指令的视图功能控制器以及在链接即可。

看来,我能摆脱在控制器一起,只是把一切都变成链接,或者是有什么我可以与控制器这么做,我可以'T与链接呢?

http://jsfiddle.net/edwardtanguay/gxr49h96/6

  .directive('itemMenu',函数(){    VAR控制器=功能($范围){
        VAR VM =这一点;
        vm.addItem =功能(){
            $ scope.add();
            vm.items.push({
                类:未定义,
                    '的firstName':'乔',
                    '姓':'牛顿',
                    时代:Math.floor(的Math.random()* 60)+ 20
            });
        };        //做同样的定义如下链接功能
        // $ scope.convertToInternal =功能(项目){
        // item.internal code =X0000;
        // item.kind ='内部';
        //};
    };    返回{
        限制:'A',
        范围: {
            项:'=',
            补充:'和;'
        },
        控制器:控制器,
        controllerAs:虚拟机,
        bindToController:真实,
        模板:'< D​​IV NG-包括=getTemplateUrl()>< / DIV>,
        链接:功能(范围,元素,ATTRS){
            scope.getTemplateUrl =功能(){
                开关(scope.item.kind){
                    案外部:
                        返回'itemMenuTemplateExternal';
                    情况下内在:
                        返回'itemMenuTemplateInternal';
                    默认:
                        回报itemMenuTemplateUndefined';
                }
            };            scope.convertToInternal =功能(项目){
                item.internal code =X0000;
                item.kind ='内部';
            };
        },
    };})


解决方案

您可能会发现很多关于控制器水汪汪的咆哮VS链接,其中大部分包含的 $编译服务文档。

直接回答这个问题,


  • 从其他模块控制器/文件可以插入通过角DI指令与控制器:'控制'


  • 控制器可依赖注入,而链接有固定的参数列表和指令的过日子依赖


  • 控制器踢链接,所以它可以prepare范围用于连接或编译某种条件的元素尽快


  • 控制器功能具有这个,其code外观符合其他OOP般ES5 code和方法之间可以很容易地转移其他code部分,例如: 服务服务或第三方code


  • 作为结果,控制器适合于被定义为<一href=\"http://blog.thoughtram.io/angularjs/es6/2015/01/23/exploring-angular-1.3-using-es6.html#angular-and-es-modules\"相对=nofollow> ES2015 或 TS 类。


  • 指令的控制器可要求 D通过子指令,并提供便捷的之间的单向互动这两个


  • 控制器利用 bindToController的:真正的 + controllerAs:虚拟机和农具 $ scope.vm 配方(尤其有用打JS原型继承),同时保持这个语法


  • bindToController 对象值提供属性绑定继承范围:真正的范围,没有更多的 $ ATTR $观察


  • bindToController 对象值提供隔离的范围进一步粒度。如果有应绑定到控制器和访问与要求,也可以做,现在的某些属性。


其中code去控制器键,其中链接更微妙的问题。

这是传统的用角控制器作为视图模型,如 MVVM (因此 controllerAs:虚拟机约定),所以如果有一个控制器工作(即服务绑定到范围值或设置范围观察者)提供给他们,离开休息到链接

由于 $ ATTRS $元素 $ transclude 本地依赖性应​​注入控制器明确,一来可能会认为这是一个标志,以跳过它们( $范围也应该被注射 $范围。 $ 方法,但我们会忽略这个事实)。

有一些关于工作的非宗教性的担忧而不是控制器应该由链接来完成。 要求 D控制器不在控制器本身可用,所以这种指令的互动发生在链接。由于控制器启动较早在编译阶段比链接,势必属​​性值将不会被插补没有,所以code依赖这些范围值变为链接。这同样适用于其他DOM相关code,它进入链接的一个原因

这主要是适当的code风格的问题,而不是真正的必要性。由于本例中的code,所有的范围东西是控制器友好的,我不认为链接应在所有在那里。

In trying to get a grasp on creating my own AngularJS directives, I have an example that does everything I need, but realize that in borrowing from various examples, I now can create functionality for the directive's view in both the controller as well as the link.

It seems that I could get rid of the controller all together and just put everything into link, or is there something that I can do with the controller that I can't do with link?

http://jsfiddle.net/edwardtanguay/gxr49h96/6

.directive('itemMenu', function () {

    var controller = function ($scope) {
        var vm = this;
        vm.addItem = function () {
            $scope.add();
            vm.items.push({
                'kind': 'undefined',
                    'firstName': 'Joe',
                    'lastName': 'Newton',
                    'age': Math.floor(Math.random() * 60) + 20
            });
        };

        // DOES THE SAME AS THE FUNCTION DEFINED BELOW IN LINK        
        //        $scope.convertToInternal = function(item) {
        //            item.internalcode = 'X0000';
        //            item.kind = 'internal';
        //        };        
    };

    return {
        restrict: 'A',
        scope: {
            item: '=',
            add: '&'
        },
        controller: controller,
        controllerAs: 'vm',
        bindToController: true,
        template: '<div ng-include="getTemplateUrl()"></div>',
        link: function (scope, element, attrs) {
            scope.getTemplateUrl = function () {
                switch (scope.item.kind) {
                    case 'external':
                        return 'itemMenuTemplateExternal';
                    case 'internal':
                        return 'itemMenuTemplateInternal';
                    default:
                        return 'itemMenuTemplateUndefined';
                }
            };

            scope.convertToInternal = function(item) {
                item.internalcode = 'X0000';
                item.kind = 'internal';
            };
        },
    };

})

解决方案

You may find a lot of watery rants about controller vs link, most of them contain the information from $compile service documentation.

Answering the question directly,

  • controllers from other modules/files can be plugged into the directive via Angular DI with controller: 'Controller'

  • controller can be injected with dependencies while link has fixed arguments list of and gets by with directive's dependencies

  • controller kicks in before link, so it can prepare the scope for linking or recompile the element on some condition ASAP

  • controller function has this, its code appearance complies to other OOP-like ES5 code, and the methods can be easily transferred between other code parts, e.g. service service or third-party code

  • as the result, controllers are suited to be defined as ES2015 or TS classes.

  • directive's controller can be required by child directive and provides convenient one-way interaction between those two

  • controller makes use of bindToController: true + controllerAs: 'vm' and implements $scope.vm recipe (particularly useful to fight JS prototypal inheritance) while keeping this syntax

  • bindToController object value provides attribute bindings for inherited scope: true scope, no more $attr.$observe

  • bindToController object value provides further granularity for isolated scope. If there are certain attributes that should be bound to the controller and accessed with require, it can be done now

Which code goes to controller and which to link is more delicate question.

It is conventional to use Angular controllers as view models, as in MVVM (hence the controllerAs: 'vm' convention), so if there is a job for controllers (i.e. binding the services to scope values or setting up scope watchers) give it to them, leave the rest to link.

Since $attrs, $element and $transclude local dependencies should be injected into controller explicitly, the one may consider it a sign to skip them ($scope should be injected too for $scope.$ methods, but we will just ignore this fact).

There are some non-religious concerns about the job that should be done by link and not by controller. required controllers aren't available in controller itself, so this kind of directive interaction takes place in link. Since controller launches at earlier compilation phase than link, bound attribute values won't be interpolated yet, so the code that depends on these scope values goes to link. The same applies to other DOM-related code, it goes to link for a reason.

It is mostly the matter of proper code style and not real necessity. As of the code in the example, all scope stuff is controller-friendly, I don't think that link should be there at all.

这篇关于在自定义指令,并`controller`有什么功能了`link`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆