gpt4 book ai didi

javascript - 使用固定次数的 ng-repeat

转载 作者:行者123 更新时间:2023-11-29 22:01:34 25 4
gpt4 key购买 nike

我想使用具有固定迭代次数的 ng-repeat。下面我试图 plunker,但我收到一个错误。所以我想知道我应该在我的代码中的什么地方写 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 指令 ​​::

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');

}
}
});

模板::

   <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>

最佳答案

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

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

查看工作 Demo

为什么 track by $index with 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

关于javascript - 使用固定次数的 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com