0

I have a list of items, some of them has property value, some has property default. And I need to bind it into the input[text] with ng-repeat.
Array is looks like:

$scope.arr = [
 {value:'name'},
 {value:'dog'},
 {default:'cat'},
 {value:'lastName'},
 {default:'ring'}
];  

And in html:

<div ng-repeat='item in arr'>
 <input type='text' ng-model='item.value || item.default'>
</div>

It works, but I have error message in console "[ngModel:nonassign] http://errors.angularjs.org/1.5.8/ngModel/nonassign?p0=item.value%20%7C%7CNaNtem.default&p1=%3Cinput%20type%3D%22text%22%20ng-model%3D%item.value%20%7C%7C%item.default%22%20class%3D%22ng-pristine%20ng-untouched%20ng-valid%22%3E". Because ng-model doesn't work with expression.. Perhaps there is another way to solve it?

Plnkr example

3 Answers 3

4

You can do it this way:

<div ng-repeat='item in arr'>
   <input type='text' ng-hide='item.default' ng-model='item.value'>
   <input type='text' ng-show='item.default' ng-model='item.default'>
</div>

Plunker example.

Sign up to request clarification or add additional context in comments.

10 Comments

thx! It's good idea, but when value = '' (empty), ng-show will hide this field. So perhaps I need to make some check like ng-show='fieldCheck(item)', and $scope.fieldCheck = function(item) {if('value' in item) return true} - for example..
@YoroDiallo Wait a minute, are you interested to show both fields? What is your final result that you expect?
yes, I need to paste all objects into input. Every object in array have default or value property, and it can be empty or have some value, but I need to bind it in input.. so when value = '' i can fill it from input (write something in input)
I am not really sure I understand what you're trying to do. If you want to have two input fields one for value another for default, then just remove the ng-show. If you want to show one or another whichever is populated, then the solution from my answer.
Ah, ok. Now I understand. WIll do a quick update on my answer just now.
|
0

You can try to create a second array, using only single type of object and bound it to the view. Then, you can watch for changes and re-assign values to your original array. It is more a MVVM approach (creating a "viewModel") that intermediate between the controller model and the view.

Comments

0

$scope.valueOrDefault = function (item){ return item.value|| item.default; }

and HTML

<div ng-repeat='item in arr'> <input type='text' ng-model='valueOrDefault(item)'> </div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.