简体   繁体   English

Angular.js指令控制器继承

[英]Angular.js Directive controller inheritance

Assume that I have a directive: 假设我有一个指令:

.directive('money', ['Service', function (Service) {
/*
* Some code
*/
controller: ['$scope', '$element', '$attrs', '$parse', function (scope, cElement, attrs, $parse) {
    scope.someValue=1;
    scope.someFunction = function(){
        console.writeline('money');
    }
}

and there is a second directive: 还有第二个指令:

 .directive('cash', ['Service', function (Service) {
    /*
    * Some code
    */
    controller: ['$scope', '$element', '$attrs', '$parse', function (scope, cElement, attrs, $parse) {
        scope.someValue=1;
        scope.someFunction = function(){
            console.writeline('cash');
        }
    }

As you can see only difference between those two directives is content of a one function. 正如您所看到的,这两个指令之间的区别仅在于一个函数的内容。 So perfect way would be inherit all the controller and shadow that someFunction 如此完美的方式将继承someFunction所有控制器和阴影

Is it even possible in angular to make something like this or I should leave two directives with so small diferences? 是否有可能在角度上制作这样的东西,或者我应该留下两个指令,如此小的差异?

Why not just have a console directive that grabs what to write from an attribute on the directive's element? 为什么不只是有一个console指令,可以从指令元素的属性中获取写入内容?

So, instead of a <div data-money></div> and <div data-cash></div> You'd have <div data-console text="money"></div> and <div data-console text="cash"></div> . 所以,而不是<div data-money></div><div data-cash></div>你有<div data-console text="money"></div><div data-console text="cash"></div>

Basically, pull what's different into attributes that can be brought into a more generic directive. 基本上,将不同的东西拉入可以带入更通用指令的属性中。


Based upon comments, how about this? 根据评论,这个怎么样? Create the controller as a standalone function, then use that same controller in both directives. 将控制器创建为独立函数,然后在两个指令中使用相同的控制器。

At this point though, I'm not sure it's going to save you much (or any) code and may be overkill for this refactoring. 但是在这一点上,我不确定它会为你节省太多(或任何)代码,并且对于这种重构可能有点过分。 Considering the minor differences, it may make more sense to just keep it the way you have it. 考虑到微小的差异,让它保持原样可能更有意义。

Yes, there are options for inheritance, It was discussed here before: AngularJS controller inheritance 是的,有继承选项,之前讨论过: AngularJS控制器继承

Edit: in addition you can take the common functionality and share it through an injected service, the variations may be passed as a parameter. 编辑:此外,您可以采用通用功能并通过注入服务进行共享,这些变体可以作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM