如何使用Angular.js添加/删除列表项onClick?

时间:2016-02-14 16:19:51

标签: javascript angularjs onclick angularjs-ng-click

我是Angular.js的新手,我每次用户点击#create-new-rule时都会添加一个lis-item,但下面似乎没有效果。

此外,当用户点击li .delete时,我希望从DOM以及this.rules数组中删除该列表项。

app.js

app.controller('RuleController', function()
{
    function Rule ()
    {
        this.name = 'untitled';

        this.delete  = function ()
        {
            console.log('removed from DOM as well as from this.rules array');
        };
    };

    this.rules = [];

    this.addRule = function () 
    {
       this.rules.push(new Rule());
    };
});

的index.html

<div id="rule-controller" ng-controller="RuleController as RuleCtrl">

  <ul id="rules">

    <li class="rule" ng-repeat="rule in RuleCtrl.rules">

         <input type="text" ng-value="rule.name"/>    
         <div class="delete" ng-click="rule.delete()">delete</div>

    </li>

  </ul>

  <div id="create-new-rule">
    <div ng-click="RuleCtrl.add()">create new rule</div>
  </div>

</div>

1 个答案:

答案 0 :(得分:1)

您的添加方法称为addRule(),但是从您调用的视图中添加add()。尝试改变它。此外,要删除您可以使用splice,但您需要在Rule函数之外获取对this的引用才能访问该数组。

E.g.index.html:

<div ng-click="RuleCtrl.addRule()">create new rule</div>

控制器:

var app = angular.module('myApp', []);
app.controller('RuleController', function()
{
    var self = this;
    function Rule ()
    {
        this.name = 'untitled';

        this.delete  = function ()
        {
           var index = self.rules.indexOf(this);
           self.rules.splice(index,1);
        };
    };

    this.rules = [new Rule()];

    this.addRule = function () 
    {
       this.rules.push(new Rule());
    };


});