Parametrise控制器可以在不同的指令中工作(Parametrise controller to work in different directives)

编程入门 行业动态 更新时间:2024-10-15 22:23:07
Parametrise控制器可以在不同的指令中工作(Parametrise controller to work in different directives)

我需要在angularJS中使用几个不同的指令。 指令具有不同的模板,控制器应以非常相似的方式工作,彼此之间的变化非常小。

我想只使用一个共享控制器,使其行为适应它所包含的指令,如代码中描述的想法:

var module = angular.module('app', []); module.directive('myFirstDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/first.html' }; }); module.directive('mySecondDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/second.html' }; }); module.controller('MyController', function ($scope) { $scope.myEvent = function () { //if it's first directive do this //if it's second directive do that }; });

这有什么办法吗?

I need to work with several different directives in angularJS. The directives have different templates and the controllers should work in very similar way, with very small changes each-other.

I was thinking to use just one shared controller that adapt its behaviour to the directive it's included like the idea described in code:

var module = angular.module('app', []); module.directive('myFirstDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/first.html' }; }); module.directive('mySecondDirective', function () { return { scope: {}, controller: 'MyController', templateUrl: './directives/second.html' }; }); module.controller('MyController', function ($scope) { $scope.myEvent = function () { //if it's first directive do this //if it's second directive do that }; });

Is there any way in angular to do this?

最满意答案

您可以在指令中使用ng-init="callback1()"和ng-init="callback2()" 。 并描述控制器中的两个回调。

You can use ng-init="callback1()" and ng-init="callback2()" in your directives. And describe both callbacks in your controller.

更多推荐

本文发布于:2023-08-06 07:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446605.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   指令   工作   Parametrise   work

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!