Angular Js - 无法读取undefined的属性'push' - 错误

时间:2015-12-28 16:01:26

标签: javascript jquery html angularjs

即时制作一个简单的应用,可以在表格中添加名称和说明。 但我得到的错误 - 无法读取undefined的属性'push'。

有人可以帮助我吗?

这是我的代码。

HTML

<div id="main">
    <!-- angular templating -->
    <!-- this is where content will be injected -->
    <div ng-view>          
    </div>
</div>

JS

var scotchApp = angular.module('scotchApp', ['ngRoute','dx']);

scotchApp.config(function ($routeProvider, $locationProvider) {

$locationProvider.html5Mode({ enabled: true, requireBase: false });

$routeProvider

    // route for the home page
    .when('/', {
        templateUrl: '/pages/home.html',
        controller: 'mainController'
    })

    .when('/new', {
        templateUrl: '/pages/edit.html',
        controller: 'newController'
    });
})

scotchApp.controller('newController', function ($scope, $location) {

$scope.person = { name: "", description: "" };

$scope.save = function () {
    $scope.crew.push($scope.person);
    $location.path("/")
}

});

scotchApp.controller('mainController', function ($scope) {
$scope.crew = [
    { name: "Hugo", description: "Programador" },
    { name: "Vitor Lopes", description: "Técnico de Informática" },
    { name: "Pedro Sousa", description: "Webdesigner" },
]   
});

HTML - new.html(我有桌子的页面)

 <table class="table table-striped" style="width: 350px;">
        <thead>
            <tr>
                <td><strong>Nome</strong></td>
                <td><strong>Descrição</strong></td>
                <td><a href="/new"><i class="glyphicon glyphicon-plus"></i></a></td>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="person in crew">
                <td>{{person.name}}</td>
                <td>{{person.description}}</td>
                <td><i class="glyphicon glyphicon-edit"></i></td>
            </tr>
        </tbody>
    </table>

HTML - new.html(我将添加新联系人的页面)

<form>
<input ng-model="person.name" placeholder="Enter Name"/><br />
<input ng-model="person.description" placeholder="Enter Description" /><br />
<button ng-click="save()" class="btn-primary">Save</button>

谢谢!!

1 个答案:

答案 0 :(得分:2)

在推送类似之前定义你的数组:

$scope.crew = []