使用固定次数的ng-repeat

时间:2014-05-03 05:40:44

标签: javascript angularjs

我想在固定次数的迭代中使用ng-repeat。下面我试图掠夺,但我得到一个错误。所以我想知道我应该在我的代码中写下getTimes()

我的代码::  plnkr.co/edit/POjQta4kFlCrJfZAFkQc?p=preview

我想要使用的内容:: http://plnkr.co/edit/j5kNLY4Xr43CzcjM1gkj?p=preview

指令::

   <my-dir 
            bgcolor="#EFF"
            my-title="Iram" 
            my-height="200"
            my-width="450"
            my-color="cyan"
            my-bgcolor="pink"
            my-collapseoption=true
            my-widgetno="1"
            save="saveChanges('custom directive')">template
          </my-dir>

ng-Directive ::

app.directive("myDir", function() {
  return {
    restrict: "E",
    scope: {
      items:"=",
      myTitle: "@",   // by value
      myHeight: "@",   // by value
      myWidth: "@",   // by value
      myColor: "@",   // by value
      myBgcolor: "@",   // by value
      myWidgetno: "@", // by reference
      myCollapseoption: "@", // by reference            
      save: "&"    // event
    },

    templateUrl:"widget.html", 
      //"<div><h2>  And This is Title{{myTitle}} </div>",
    replace: true,
    transclude: false,
    link: function (scope, element, attrs) {

        // show initial values: by-val members will be undefined
       console.log("items is " +scope.items);


        // change element just to show we can
        element.css("background", attrs.myBgcolor);
        element.css("color", attrs.myColor);
        element.css("width", attrs.myWidth+'px');
       // element.css("height", attrs.myHeight+'px');

    }
  }
});

Template ::

   <div>

<div class="panel panel-primary" ng-repeat="t in getTimes(4) | limitTo:2"> 
            <div class="panel-heading"> 
                <span class="glyphicon glyphicon-th-large"></span>{{myTitle}}{{items}}
                <div class="btn-group pull-right">
                    <button type="button" class="btn btn-default btn-xs" ng-show="myCollapseoption" ng-click="checked=!checked">
                        <span class="glyphicon glyphicon-chevron-down "></span>
                    </button>                        
                </div>
            </div>
            <div class="panel-body collapsible" ng-init="checked=true" ng-show="checked"  ng-style="{'background-color':'pink'}" style="clear:both;">
            This is the middle Content <br/><br/><br/>
            </div>
        </div>
  </div>  

1 个答案:

答案 0 :(得分:2)

您需要为该指令编写controller。 像这样:

controller: function($scope) {
     $scope.getTimes=function(n){
        return new Array(n);
     };  
}

见工作Demo

为什么track by $index使用ng-repeat

当您返回具有重复值的数组时,它将抛出不允许重复值的错误。你可以像我一样使用track by来解决这个问题,或者你可以修改getTimes函数来创建一个具有唯一值的数组。

<强>更新

当你传递变量时,它不起作用,因为值是字符串。

var a = new Array("3")

上述语句将创建一个长度为1的数组,即[“1”]。这就是问题所在。

您需要更新语句如下:

controller: function($scope) {
     $scope.getTimes=function(n){
         return new Array(parseInt(n));
     };  
}

更新了代码 - See here