如何在Angular中打印新对象的属性值?

时间:2016-02-10 18:52:05

标签: javascript angularjs javascript-objects

我正在开发一个列表应用程序,最初向用户显示一个输入和按钮。在输入中,用户输入新列表的名称,并且在单击该按钮之后,出现空列表以准备输入项目。添加/删除列表项也可以添加新列表。但列表的名称不会在页面上打印。目前没有任何高级CSS,所有列表的名称都应该出现在页面顶部而不是直接位于各自列表的上方。

https://codepen.io/anon/pen/RVmeLe

HTML:

    <div ng-app="notepadApp">
    <div ng-controller="notepadController as notepadCtrl">
        <header ng-repeat="list in notepadCtrl.lists">
            <form name="removeListForm" ng-submit="notepadCtrl.removeList($index)">
                <input type="submit" value="Remove list">
            </form>
            <h1>{{list.name}}</h1>
        </header>
        <div ng-repeat="list in notepadCtrl.lists" class="shoppingList" ng-controller="ItemController as itemCtrl">
            <ul>
                <li ng-repeat="item in list.items">

                    <label>
                        <input type="checkbox" ng-model="item.checked">
                        <span class="item-name-wrapper">{{item.name}}</span>
                    </label>
                    <form name="itemForm" ng-submit="itemCtrl.removeItem(list, $index)">
                        <input type="submit" value="remove">
                    </form>

                </li>
            </ul>
            <form name="itemForm" ng-submit="itemCtrl.addItem(list)">
                <input type="text" ng-model="itemCtrl.item.name">
                <input type="submit" value="Add item">
            </form>
        </div>

        <form name="addListForm" ng-submit="notepadCtrl.addList(newListName)">
            <input type="text" ng-model="notepadCtrl.list.name">
            <input type="submit" value="Add list">
        </form>
    </div>
</div>

使用Javascript:

(function(){

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

var shoppingLists = [

];

app.controller('notepadController', function(){
    var notepadCtrl = this;

    notepadCtrl.lists = shoppingLists;

    notepadCtrl.addList = function(newListName) {
        var newList = {
            name: newListName,
            items:[]
        };

        shoppingLists.push(newList);
    };

    notepadCtrl.removeList = function(index) {
        shoppingLists.splice(index, 1);
    };

});

app.controller('ItemController', function(){
    this.item = {};

    this.addItem = function(list){
        list.items.push(this.item);
        this.item = {};
    };

    this.removeItem = function(list, index) {
        list.items.splice(index, 1);
    };
});
})();

1 个答案:

答案 0 :(得分:0)

您只想替换:

ng-submit="notepadCtrl.addList(newListName)"

使用:

ng-submit="notepadCtrl.addList(notepadCtrl.list.name)"