为什么这个angularjs代码不起作用?

时间:2015-10-22 01:28:29

标签: angularjs

其他人的小提琴都在工作,我的代码基于他们的代码,但由于某种原因它无法正常工作。

http://jsfiddle.net/prarg2zg/1/

我看到大括号时通常消失的花括号。

HTML

<div ng-controller="MyCtrl">
    <table>
        <thead>
            <th>Name</th>
            <th>Age</th>
        </thead>
        <tr ng-repeat="person in people">
            <td>{{name}}</td>
            <td>{{age}}</td>
        </tr>
    </table>
</div>

JS

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.people = [{
        name: "test",
        age: 18
    }, {
        name: "test2",
        age: 18
    }, {
        name: "Test1",
        age: 18
    }];
}

2 个答案:

答案 0 :(得分:2)

姓名和年龄不在范围内,但每个person都是。从您控制器中构建的人物中拉出属性:

<div ng-controller="MyCtrl">
    <table>
        <thead>
            <th>Name</th>
            <th>Age</th>
        </thead>
        <tr ng-repeat="person in people">
            <td>{{person.name}}</td>
            <td>{{person.age}}</td>
        </tr>
    </table>
</div>

您还需要将控制器注册到您的应用程序:

var myApp = angular.module('myApp', []);



function MyCtrl($scope) {
    $scope.people = [{
        name: "test",
        age: 18
    }, {
        name: "test2",
        age: 18
    }, {
        name: "Test1",
        age: 18
    }];
}

myApp.controller('MyCtrl', ['$scope', MyCtrl]);

在小提琴中工作:http://jsfiddle.net/prarg2zg/5/

答案 1 :(得分:2)

两件事:

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <table>
            <thead>
                <th>Name</th>
                <th>Age</th>
            </thead>
            <tr ng-repeat="person in people">
                <td>{{person.name}}</td>
                <td>{{person.age}}</td>
            </tr>
        </table>
    </div>
</div>

缺少ng-app

不使用person.nameperson.age

更新了小提琴:http://jsfiddle.net/KyleMuir/prarg2zg/4/

相关问题