gpt4 book ai didi

javascript - Angular JS 将字符串数组传递给指令

转载 作者:行者123 更新时间:2023-12-02 16:00:45 25 4
gpt4 key购买 nike

我有以下指令,它从数组数据中输出数字和相应的字符串值。

var app = angular.module("test",[]);

app.controller("Ctrl1",function($scope){
$scope.range = 5;
$scope.data = ['a','b','c','d','e',];
});
app.directive("myDirective", function(){
return {
restrict: "EA",
scope: true,
template: "<div ng-repeat='n in [] | range:range'>{{n + 1}} - {{data[n]}}</div>"
};
})
.filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="Ctrl1">
<label>Edit range </label> <input ng-model="range" /><br>
<label>edit data </label> <input ng-model="data" /><br>
<my-directive></my-directive>
</div>
</div>

这在加载时按预期运行,但是当用户编辑 ng-model="data" 时,输出会中断,因为它包含 , 作为大批。

实现此功能的最佳方法是什么,以便当用户更新数据时指令仍然像最初一样处​​理数组? (如果需要,我很乐意用逗号分隔数据中的项目或使用其他方法,例如 | 。)

最佳答案

更好的方法是使用一个函数来推送和弹出数组中的输入数据。类似于以下内容:

HTML:

<input type="text" ng-model="inputdata" ng-click="pushDataInArray(inputdata);"></input>
//And similarly have a function to pop the data from whichever index from the array.

JS:

$scope.pushDataInArray = function(inputdata){
$scope.data.push(inputdata);
};

在我看来,这将是一个更好的方法。

关于javascript - Angular JS 将字符串数组传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31218454/

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