如何使用Angular Js将对象正确提交到数组中

时间:2016-10-04 10:17:59

标签: javascript angularjs

我试图学习AngularJs并编写一些丢弃代码。我试图创建一个对象Bookmark并将其推入一个数组。

HTML:

<h2>Create a new bookmark </h2>
                <form class="form-group" ng-submit="createBookmark(newBookmark)" novalidate>
                    <!--Title-->
                    <h4>Bookmark Title</h4>
                    <input type="text" ng-model="newBookmark.title">
                    <!--Url-->          
                    <h4>Bookmark Url</h4>
                    <input type="text" ng-model="newBookmark.url">
                    <!--Submit-->
                    <button type="submit" href="#" class="btn btn-primary" id="crForm" ng-click="stopCreating()">Save</button>
                </form>

JS:

function resetCreateForm(){
        $scope.newBookmark = {
            title : '',
            url : '',
            category : $scope.currentCategory.name
        };   
    }

    function createBookmark(bookmark) {
        bookmark.id = $scope.bookmarks.length;
        bookmark.category = $scope.currentCategory.name;
        $scope.bookmarks.push(bookmark);

        resetCreateForm();
    }
    $scope.createBookmark = createBookmark;
    $scope.resetCreateForm = resetCreateForm;

对象:

$scope.bookmarks = [
        {id: 0, title: "Title1", url: "www.Title1.com", category: "Development"},
        {id: 1, title: "Title2", url: "www.Title2.com", category: "Development"}

];

模块和控制器:

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

app.controller('listController', function($scope){

由于某些原因它不起作用,到目前为止我认为它是由Angular版本的变化引起的,但我找不到让它工作的方法。

1 个答案:

答案 0 :(得分:1)

你必须绑定resetCreateForm&amp;控制器createBookmark中的$scope,以便您可以从视图中访问它们。

//place this inside your controller
$scope.resetCreateForm = resetCreateForm;
$scope.createBookmark= createBookmark;

此外,您无需在ng-click上调用功能,点击按钮ng-submit即可调用。删除ng-click="stopCreating()"