provola provola - 1 year ago 57
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

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

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

Answer Source

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:

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

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>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download