【问题标题】:How do I use an attribute directive inside an element directive template in angularjs?如何在 angularjs 的元素指令模板中使用属性指令?
【发布时间】:2017-04-03 17:04:47
【问题描述】:

我需要在我的网站上列出产品和其他项目的复选框列表。 checklist-model 属性指令适用于此,因为我可以将其绑定到与所选项目相关的项目列表。

当我简单地在我的角度控制器中使用此代码时,所有这些都可以正常工作。但是,我有几个列表框需要以相同的方式显示,每个列表都使用相同的“全选”和“全选”按钮。我不想重复这段代码和布局,所以我为整个列表创建了自己的指令。

问题是当我使用我自己的指令时,它没有正确绑定回我的数据,全选只能工作一次,而全选则根本不起作用。

我怀疑这与我传递范围的方式有关,并且这两个指令不能很好地协同工作。

为什么这在指令中不起作用?

这是一个 jsfiddle:https://jsfiddle.net/fande455/m9qhnr9c/7/

HTML

<section ng-app="myApp"   ng-controller="couponEditController">
<script type="text/ng-template" id="checkboxlist.template.html">
  <div>
    <div class="form-input form-list">
      <label ng-repeat="item in valuelist | orderBy:value">
        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item[value]}}
        <br />
      </label>
    </div>
    <button class="btn btn-default" style="float:left; margin-bottom: 5px;margin-left: 10px;margin-right:10px" ng-click="selectNone()">Select None</button>
    <button class="btn btn-default" style="float:left; margin-bottom: 5px;" ng-click="selectAll()">Select All</button>

    <div class="cleared"></div>
  </div>
</script>

<div>
  <checkboxlist model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</div>
</section>

JS

var myApp = angular.module('myApp', ['checklist-model']);

myApp.directive('checkboxlist', [function() {
  return {
    restrict: 'E',
    templateUrl: 'checkboxlist.template.html',
    controller: 'checkboxlistController',
    scope: {
      model: "=",
      value: "@",
      valuelist: "="
    },
    require: '^checklist-model'
  }
}]);

myApp.controller('checkboxlistController', ['$scope', function($scope) {

  $scope.selectAll = function() {
    $scope.model = angular.copy($scope.valuelist);
  };

  $scope.selectNone = function() {
    $scope.model = [];
  };
}]);

myApp.controller('couponEditController', ['$scope', function($scope) {

  $scope.coupon = 
    {"Id": 1,
    "Name": "My Coupon",
    "Products": []
    }
  ;

  $scope.productsList = [{
    "Id": 1,
    "Name": "Product 1"
  }, {
    "Id": 2,
    "Name": "Product 2"
  }];
}]);

【问题讨论】:

    标签: javascript angularjs angularjs-directive checklist-model


    【解决方案1】:

    来自文档:

    与其做 checklistModelList = [] 不如做 checklistModelList.splice(0, checklistModelList.length)

    在你的代码中你应该这样做

    $scope.selectAll = function() {
        $scope.selectNone();
        $scope.model.push.apply($scope.model, $scope.valuelist);
    };
    
    $scope.selectNone = function() {
        $scope.model.length = 0;
    };
    

    这是更新后的小提琴:https://jsfiddle.net/m9qhnr9c/9/

    这个想法不是用一个新的数组替换数组,而是只修改它的元素。

    【讨论】:

    • 修复了它。我的问题是为什么?还有,当它不在指令中时,为什么它会按照我的方式工作?
    • 因为指令内部正在创建一个新范围。
    猜你喜欢
    • 2015-06-06
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多