简体   繁体   中英

How do I add/remove a list-item onClick using Angular.js?

I am new to Angular.js and what I'm trying to do is adding a lis-item every time the user clicks on #create-new-rule but the below doesn't seem to be working.

Also, when the user click on li .delete I want that list-item to be removed from the DOM as well as from the this.rules array.

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>

Your method for adding is called addRule() but from the view you are calling add(). Try changing that. Furthermore, to remove you can use splice, but you would need to get a reference to this outside of the Rule function in order to access the array.

Egindex.html:

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

Controller:

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());
    };


});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM