2016-02-12 47 views
2

我在看约翰爸爸风格角度最佳实践。 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?如果我收到一组数据,我应该使用或vm.data下的scope.data控制器吗?非常感谢!

回答

1

以下几个原则来考虑:

  • 的基本区别是,控制器可以公开的API,和链接功能可以使用需要与控制器进行交互。 最佳实践当您想将API暴露给其他指令时使用控制器。否则使用链接。Angular docs

  • 写业务逻辑控制器和DOM操作的链接

更直截了当的回答:

由于$scope(在控制器)== vm(在控制器)== scope(在链接中),您可以在linkFucn或vm.data下执行scope.data。

您还没有注入到服务链接功能,而到控制器。

只是我的理解...

相关问题