blue-sky
blue-sky

Reputation: 53806

How to fix this AngualrJS data-ng-init binding - beginner

I'm following this AngularJS tutorial : http://www.youtube.com/watch?v=i9MHigUZKEM

Here is a snippet of code :

<html data-ng-app="">

<body data-ng-init="names=[{'John Smith'} , {test}]">

Name : 
<br />
<input type = "text" data-ng-model="name" /> {{name}}

<h3>Looping with the ng-repeat Directive</h3>

<br />
<ul>
    <li data-ng-repeat="personName in names" {{personNamde
</ul>


<script src="angular.min.js"></script>

</body>
</html>

The line <body data-ng-init="names=[{'John Smith'} , {test}]">

is causing the exception :

Error: [$parse:syntax] http://errors.angularjs.org/undefined/$parse/syntax?p0=%7D&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=21&p3=names%3D%5B%7B'John%20Smith'%7D%20%2C%20%7Btest%7D%5D&p4=%7D%20%2C%20%7Btest%7D%5D
    at Error (<anonymous>)
    at file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:6:453
    at Ya.throwError (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:152:398)
    at Ya.consume (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:153:359)
    at Ya.object (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:161:39)
    at Ya.primary (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:152:33)
    at Ya.unary (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:158:273)
    at Ya.multiplicative (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:158:6)
    at Ya.additive (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:157:376)
    at Ya.relational (file:///C:/workspaces/04072013/AngularJSFirst/WebContent/angular.min.js:157:240) <body data-ng-init="names=[{'John Smith'} , {test}]"> angular.min.js:83

It seems to be complaining about the use of '{' brackets ?

Is the code correct ?

Upvotes: 1

Views: 5378

Answers (2)

NicolasMoise
NicolasMoise

Reputation: 7279

While Arun's answer is technically correct, you shouldn't use ng-init for this purpose, instead, define names inside your controller. ng-init should only be used in special cases such as nested ng-repeats, see their docs http://docs.angularjs.org/api/ng.directive:ngInit and the little red box.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388326

Try

<div data-ng-init="names=['John Smith' , 'test']">
    Name : 
    <br />
    <input type = "text" data-ng-model="names[1]" /> {{names[1]}}

    <h3>Looping with the ng-repeat Directive</h3>

    <br />
    <ul>
        <li data-ng-repeat="personName in names"> {{personName}}</li>
    </ul>
</div>

Demo: Fiddle

Upvotes: 1

Related Questions