I have the below directive, which outputs the number and the corresponding string value from the array data.
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>
This runs as expected on load however when the user edits the ng-model="data"
the output breaks as it is including the ,
as an item in the array.
What is the best way to get this working so that when the user updates the data the directive still treat the array like it did initially? (I am happy to either comma seprate items in data or another method such as | if required.)
The better way would be to have a function to push and pop the input data in the array. Something like the following :
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);
};
This would be a better approach IMO.