AngularJs: List not showing in ng-Bind or ng-model

469 views Asked by At

Beginner to angular.

I have a list, list1 = ["item1"].

I wanted to bind the whole list to a label. In other words: <label> {{list1}} </label>. This will output ["item1"]. It looked tacky, so I tried using ng-bind. <label ng-bind = "list1"> </label>. This failed to show me ANY output (blank label). Why did this not work?

Second try, I did this <label ng-bind = "list1[0]">. This worked!! Why?

Now, I wanted to try ng-model on that. <label ng-model = "list1"> </label>. Did not work. Then I tried, <label ng-model = "list1[0]">. No luck...ugh! I cant get my head around this scenario at all.

I tried finding the difference between ng-bind and ng-model. Found this here. If that answer is valid, why <label ng-bind = "list1"> </label> DOES NOT EQUAL <label> {{list1}} </label>?

1

There are 1 answers

0
ajmajmajma On

Becasue when you do {{list1}} you are two way binding the whole varaible, which happens to be an array, so it displays it as such. You could do

{{list1[0]}}

If you want to get the same desired effect

And for ng-bind - from the documentation itself

The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.

So it will replace the text content of whatever you have bound with the value, since you have an array of strings, it pulls out the string.

Check here for examples - http://jsfiddle.net/U3pVM/16563/

The first {{}} expression just prints the whole object, the second specifies the item in the array by index, and the third prints each item in the array as text (comma separated)

Just to add one last comment on, if your variable was a string like

$scope.list1 = "list1"

Then you would get the same effect between the ng-bind and the {{}}