provola provola - 3 months ago 9
AngularJS Question

Find the object in the $scope that have a key starting with a certain string?

I have a list of text field like this

<ul>
<li><input type="text" name="option1" ng-model="option1" /></li>
<li><input type="text" name="option2" ng-model="option2" /></li>
</ul>


I'd like to find all of the option* that are in the $scope
Thank you in advance for the answer

Answer

I would make an array which will hold the input data and then add a loop to iterate over this array in html. You will then not need to search in scope for specific objects, you will have the array ready.

$scope.allOptions = [
    {name: 'option1', text: ''},
    {name: 'option2', text: ''}
];

And then:

<ul>
    <li ng-repeat="option in allOptions"><input type="text" name="{{option.name}}" ng-model="option.text" /></li>
</ul>

P.s. not tested, let me know how does it works and I will help if something fails.

The problems is that I don't know the number of the text fields in the list. The application has by default two list but there is also a button that permit the user to add new options programmatically. So with Jquery i add in every text field a progressive number in the ng-model. The first ng-model=option1, the second option2, ...

I recommend to use angular then (to add another input).

$scope.addInput = function(){
    var n = $scope.allOptions.length;
    $scope.allOptions.push({name: 'option'+(n+1), text: ''});
};

<button ng-click="addInput()">Awesomeness is here</button>