如何修复此AngularJS数据-ng-init绑定 - 初学者

时间:2013-11-15 14:48:30

标签: javascript jquery angularjs

我正在关注这个AngularJS教程:http://www.youtube.com/watch?v=i9MHigUZKEM

以下是一段代码:

<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>

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

导致异常:

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

似乎在抱怨使用'{'括号?

代码是否正确?

2 个答案:

答案 0 :(得分:1)

尝试

<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>

演示:Fiddle

答案 1 :(得分:1)

虽然Arun的答案在技术上是正确的,但您不应该为此目的使用ng-init,而是在控制器内定义names。 ng-init只能用于特殊情况,例如嵌套的ng-repeats,请参阅他们的文档http://docs.angularjs.org/api/ng.directive:ngInit和小红框。