AngularJS:没有控制器的指令如何工作

Mon*_*kar 3 angularjs angularjs-directive angularjs-scope

只是从这个链接阅读一篇文章http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-6-using-controllers

像 ng 新手一样,我很难理解他们的代码示例。告诉我一个例子,人们会在没有控制器的情况下编写指令?

他们的代码

(function() {

  var app = angular.module('directivesModule');

  app.directive('isolateScopeWithController', function () {

    var controller = ['$scope', function ($scope) {

          function init() {
              $scope.items = angular.copy($scope.datasource);
          }

          init();

          $scope.addItem = function () {
              $scope.add();

              //Add new customer to directive scope
              $scope.items.push({
                  name: 'New Directive Controller Item'
              });
          };
      }],

      template = '<button ng-click="addItem()">Add Item</button><ul>' +
                 '<li ng-repeat="item in items">{{ ::item.name }}</li></ul>';

      return {
          restrict: 'EA', //Default in 1.3+
          scope: {
              datasource: '=',
              add: '&',
          },
          controller: controller,
          template: template
      };
  });

}());
Run Code Online (Sandbox Code Playgroud)

指令用法:

属性<div isolate-scope-with-controller datasource="customers" add="addCustomer()"></div>

元素<isolate-scope-with-controller datasource="customers" add="addCustomer()"></isolate-scope-with-controller>

我们如何将客户数据直接传递给指令。基本上我们在控制器中有模型并填充模型,然后通过隔离范围或指令使用控制器范围将该模型数据传递给指令。我对上面的代码如何工作感到非常困惑,请帮助我理解。谢谢

小智 5

正在考虑的场景意味着该指令将在应用程序的一部分中使用,该部分已经声明了控制器,其范围包含属性datasourceadd. 反过来,将为指令的每个实例实例化新的控制器,并将拥有自己的隔离范围。

实际上,创建没有控制器而是使用链接函数的指令更为常见。这些指令可以依赖父控制器,有时执行 DOM 操作,绑定到 JS 事件,或者只是作为封装应用程序的一部分的手段。

您可以在此处找到不创建自己的控制器的指令的一个很好的示例。它取自 Angular文档。在这种情况下,您会发现它甚至不属于父作用域,这意味着不涉及任何控制器。实际上,像这样的元素很可能会向父控制器报告,然后父控制器会对该位置做一些事情。

您可以在此处阅读有关指令、链接函数以及指令如何与控制器一起工作的更多信息。