动态元素未在AngularJS上调用指令方法

Dynamic element not calling directive method on a AngularJS

本文关键字:调用 指令 方法 AngularJS 元素 动态      更新时间:2023-09-26

我使用该指令的目的是创建一个SelectAll指令,该指令可以附加到任何类型的html元素上以供重用。

咖啡描述:

App.directive "selectAll", [ ->
  restrict: 'A',
  replace : true,
  scope: {
    attribute: '@',
    collection: '='
  },  
  link: (scope, element, attrs, model) ->
    scope.selected = false
    element.attr 'ng-click', 'toggle_selection()'
    element.html "<i class='icon-check icon-white''></i>Select All"
    scope.toggle_selection = () ->
      scope.selected = !scope.selected
      collection.forEach (item) ->
        item[attribute] = scope.selected
      scope.toggle_content()
    scope.toggle_content = () ->
      element.html("<i class='icon-check icon-white'></i>Select All") unless scope.selected
      element.html("<i class='icon-check-empty icon-white'></i>Unselect All") if scope.selected
]

Javascript:

App.directive("selectAll", [
    function() {
      return {
        restrict: 'A',
        replace: true,
        scope: {
          attribute: '@',
          collection: '='
        },
        link: function(scope, element, attrs, model) {
          scope.selected = false;
          element.attr('ng-click', 'toggle_selection()');
          element.html("<i class='icon-check icon-white''></i>Select All");
          scope.toggle_selection = function() {
            scope.selected = !scope.selected;
            collection.forEach(function(item) {
              return item[attribute] = scope.selected;
            });
            return scope.toggle_content();
          };
          return scope.toggle_content = function() {
            if (!scope.selected) {
              element.html("<i class='icon-check icon-white'></i>Select All");
            }
            if (scope.selected) {
              return element.html("<i class='icon-check-empty icon-white'></i>Unselect All");
            }
          };
        }
      };
    }
  ]);

问题是没有调用togg_selection函数。我试图对我动态创建的元素调用$compile,但它引发了一个异常,表示未定义compile。

此外,如果你有更好的方法来做我正在做的事情,请分享最佳实践,因为我使用Angular的时间不到一周。

谢谢!

我没有发现原因,所以我改变了使用模板atribute的方法,正如@Chandermanji 在赞扬中所建议的那样

App.directive "selectall", [ ->
  restrict: 'E',
  replace : true,
  scope: {
    attribute: '@',
    collection: '='
  },
  template: '<div class="btn btn-large btn-inverse" ng-click="toggle_selection(collection, attribute)">' +
      '<i class="icon-check icon-white"></i>Select All' +
    '</div>',
  link: (scope, element, attrs, model) ->
    scope.selected = false
    scope.toggle_selection = (collection, attribute) ->
      scope.selected = !scope.selected
      scope.collection.forEach (item) ->
        item[attribute] = scope.selected
      scope.toggle_content()
    scope.toggle_content = () ->
      element.html("<i class='icon-check icon-white'></i>Select All") unless scope.selected
      element.html("<i class='icon-check-empty icon-white'></i>Unselect All") if scope.selected
]