简体   繁体   中英

how to add item in array in angular js?

I want to make two directives communicate. I have two directives: one is table directive , the other one is header directive . On header I have two buttons "add" and delete . I want to add an element in the list on click of add button, and delete the element when user clicks the delete button.

But the list is a different directive, how I can update the array after delete and add actions?

Here is my code.

.directive('tm',function(){
    return {
        restrict: 'E',
        templateUrl: 'login.html',
        scope: {
        },
        controller: 'f',
        controllerAs: 'vm'

    };
})

.controller('f',function($http, $scope){           
    var vm = this;
    $http.get('data.json').success(function(data){
      vm.data = data;
    })      
})

.controller('abc',function($http, $scope){

})

.directive('h',function(){
    return {
        restrict: 'E',
        templateUrl: 'header.html',
        scope: {
        },
        controller: 'he',
        controllerAs: 'h'

    };
})

.controller('he',function($http, $scope){
    var h =this;
    h.add=function(){
        alert('heelo')
    }

    h.delete=function(){
        alert('delete')
    }

})

I need user to push the default value ({name: 'abc', lastname: 'pqr'}) in the list when clicks the add button and it should update the list. When user clicks delete, it deletes the last element and updates the list.

Update plunker server is not running

I make fiddle https://jsfiddle.net/8fjhLqnw/

I need to add a item in list when add button is press..and delete an item when delete button is press

First create service to share data and functions like this:

service('sharedData', function(){
    var vm = this;
    vm.list = [];
    vm.add=function(item){
        vm.list.push(item);
    }

    vm.get = function(){
        $http.get('data.json').success(function(data){
            vm.data = data;
        })
    }
    vm.delete=function(item){
        // use slice for delete object from list
    }
})

then you must inject this service in your directives:

controller('he', function($http, $scope, sharedData)

and use sharedData in your functions:

h.add=function(item){
    sharedData.add(item)
}

Here is code

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