Kawd
Kawd

Reputation: 4440

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>

Upvotes: 1

Views: 1908

Answers (1)

Rei Mavronicolas
Rei Mavronicolas

Reputation: 1435

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.

E.g.index.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());
    };


});

Upvotes: 1

Related Questions