gpt4 book ai didi

angularjs - Controller 可以完全被指令中的链接函数取代吗?

转载 作者:行者123 更新时间:2023-12-03 08:17:00 24 4
gpt4 key购买 nike

我正在阅读这篇文章:

http://teropa.info/blog/2014/10/24/how-ive-improved-my-angular-apps-by-banning-ng-controller.html

它建议将 Controller 集成到这样的指令中,以消除使用 ng-controller 的需要:

angular.module('contestantEditor', [])
.directive('cContestantEditorForm', function() {
return {
scope: {
contestants: '='
},
templateUrl: 'contestant_editor.html',
replace: true,
controller: 'ContestantEditorFormCtrl',
controllerAs: 'ctrl',
bindToController: true
};
})
.controller('ContestantEditorFormCtrl', function($scope) {

this.contestant = {};

this.save = function() {
this.contestants.push(this.contestant);
this.contestant = {};
};

});

然而,在评论中,其他人提出了这个解决方案:
angular.module('contestantEditor', [])
.directive('cContestantEditorForm', function () {
return {
scope: {
contestants: '='
},
templateUrl: 'contestant_editor.html',
replace: true,
link: function (scope) {
scope.contestant = {};

scope.save = function() {
scope.contestants.push(scope.contestant);
scope.contestant = {};
};
}
};
});

它实现了与带有 Controller 的版本完全相同的功能,而无需制作 Controller 。所以我很好奇这两种方法的优缺点与传统上使用 ng-controller 编写 angular 相比,以及 Controller 是否在结束时是必要的。

Here是第一个的plunker,和 here是第二个。

最佳答案

指令 ,您应该尽可能使用链接功能。仅在需要与其他指令通信时才使用 Controller 。

您可以找到有关此讨论的更多信息 here .特别是这个最佳实践声明:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

关于angularjs - Controller 可以完全被指令中的链接函数取代吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27949398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com