了解角度控制器Vs指令

Jos*_*osh 3 javascript angularjs

我对angularjs很新.我试图理解为什么使用这个指令比使用控制器更好.两个示例都输出相同的值.

指令示例:

angular.module('docsSimpleDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.customer = {
    name: 'Naomi',
    address: '1600 Amphitheatre'
  };
}])
.directive('myCustomer', function() {
  return {
    template: 'Name: {{customer.name}} Address: {{customer.address}}'
  };
});
Run Code Online (Sandbox Code Playgroud)

标记:

<div ng-controller="Controller">
  <div my-customer></div>
</div>
Run Code Online (Sandbox Code Playgroud)

控制器示例:

angular.module('docsSimpleDirective', [])
    .controller('Controller', ['$scope', function($scope) {
      $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
      };
    }])
Run Code Online (Sandbox Code Playgroud)

标记:

<div ng-controller="Controller">
   Name: {{customer.name}} Address: {{customer.address}}     
 </div>
Run Code Online (Sandbox Code Playgroud)

也许我只是不完全理解指令.

Pje*_*etr 5

在工作中,我们使用简单的练习来查看是否需要指令.如果某个代码段被多次使用,我们会将其转换为指令.

指令还有机会为模板添加更少的混乱.

angular.module('DocsSimpleDirective', [])
    .controller('DocsController', [function() {
        this.customer = {
            name: 'Naomi',
            address: '1600 Amphitheatre'
        };
    }])
    .directive('myCustomer', function() {
        return {
            scope: true
            restrict: 'EA',
            controller: 'DocsController',
            controllerAs: 'docsCtrls',
            templateUrl: 'assets/template/my-customer.directive.html'
        };
    })
;
Run Code Online (Sandbox Code Playgroud)

将允许您的模板定义为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular test</title>
</head>
<body ng-app="DocsSimpleDirective">
    <my-customer></my-customer>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

和你的指令:

<article>
    <strong>{{ docsCtrls.customer.name }}</strong><br>
    {{ docsCtrls.customer.address }}
</article>
Run Code Online (Sandbox Code Playgroud)

就个人而言,我试图避免使用$scope绑定数据.如果其他人开始阅读你的代码,那么customer在某个控制器上的某个控制器中定义的魔法比某个控制器上的变量更难识别.

隔离$ scope可能很有用(通过定义scope: true)来使用默认值.如果你需要停止隔离你的指令,它应该是你想到的,而不是因为它是默认值.
当你没有隔离一个作用域时,它继承了$parentScope嵌套指令时在这个中定义的所有值,其中所有指令都应该知道它们来自哪个父类.这有一个非常明显的危险,您可以操纵不应被操纵的parentcope中的数据.

https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope