0

我对这个指令的意图是创建一个 Select-All 指令,它可以附加到任何类型的 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");
            }
          };
        }
      };
    }
  ]);

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

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

谢谢!

4

1 回答 1

0

我没有发现原因,所以我改变了使用模板属性的方法,正如@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
]
于 2013-07-01T15:04:49.183 回答