我正在寻找John Papa风格的角度最佳练习。 https://github.com/johnpapa/angular-styleguide#directives
但是,我对他的指导风格有疑问。
angular
.module('app')
.directive('myExample', myExample);
function myExample() {
var directive = {
restrict: 'EA',
templateUrl: 'app/feature/example.directive.html',
scope: {
max: '='
},
link: linkFunc,
controller: ExampleController,
// note: This would be 'ExampleController' (the exported controller name, as string)
// if referring to a defined controller in its separate file.
controllerAs: 'vm',
bindToController: true // because the scope is isolated
};
return directive;
function linkFunc(scope, el, attr, ctrl) {
console.log('LINK: scope.min = %s *** should be undefined', scope.min);
console.log('LINK: scope.max = %s *** should be undefined', scope.max);
console.log('LINK: scope.vm.min = %s', scope.vm.min);
console.log('LINK: scope.vm.max = %s', scope.vm.max);
}
}
ExampleController.$inject = ['$scope'];
function ExampleController($scope) {
// Injecting $scope just for comparison
var vm = this;
vm.min = 3;
console.log('CTRL: $scope.vm.min = %s', $scope.vm.min);
console.log('CTRL: $scope.vm.max = %s', $scope.vm.max);
console.log('CTRL: vm.min = %s', vm.min);
console.log('CTRL: vm.max = %s', vm.max);
}
<!-- example.directive.html -->
<div>hello world</div>
<div>max={{vm.max}}<input ng-model="vm.max"/></div>
<div>min={{vm.min}}<input ng-model="vm.min"/></div>
在他的例子中,他将控制器和指令都放在一个文件中。我的问题是如何知道我的代码的哪一部分位于linkFunc
下,哪些部分位于ExampleController
之下?例如,如果我想注入服务,是否应该将其添加到linkFunc
?如果我收到一组数据,是否应该在控制器下的scope.data
或linkFucn
下使用vm.data
?非常感谢!
答案 0 :(得分:1)
Here few principles to consider:
The basic difference is that controller can expose an API, and link functions can interact with controllers using require. Best Practice: use controller when you want to expose an API to other directives. Otherwise use link. Angular docs
write business logic in controller and DOM manipulation in link
More straight forward answer:
Since loop.create_task()
(in controller) == $scope
(in controller) == vm
(in link), you can do both scope.data under linkFucn or vm.data.
You are not injecting services into link function, rather into controller.
Just my understanding ...