3

I have a list of items which are a custom directive and each of those items has a remove button. Now I want to disable this remove button when there is only one item left in my list, but for some reason it doesn't work as expected.

I've made a plunker example where you an watch this behavior.

I guess there is something wrong with the canRemove: '&' part of my directive. But I don't know how to get it working.

View:

<body ng-controller="MainCtrl as vm">
    <div ng-repeat="item in vm.items">
        <my-directive item="item"
                      canRemove="vm.items.length != 1"
                      remove="vm.remove(item)">
        </my-directive>
    </div>
</body>

Controller:

app.controller('MainCtrl', function($scope) {
    var vm = this;

    vm.items = [
        {
            number: 1
        } , {
            number: 2
        }
    ];

    vm.remove = function(item) {
        vm.items.splice(vm.items.indexOf(item), 1);
    }
});

Directive:

app.directive('myDirective', function() {
    return {
        restrict: 'EA',
        scope: {
            item: '=',
            canRemove: '&',
            remove: '&'
        },
        controller: function() {
            var vm = this;

            vm.onRemove = function() {
                vm.remove({ item: vm.item });
            };
        },
        controllerAs: 'vm',
        bindToController: true,
        template: '<button ng-disabled="!vm.canRemove" ng-click="vm.onRemove()">' + 
                  '    Remove {{ vm.item.number }}' +
                  '</button>'
    }
});

PS: Since I'm pretty new to angular is the way I'm handling the removing of the items a good practice? Or should I use broadcast and on instead?

1 Answer 1

2

First of all attribute should look like can-remove:

<my-directive item="item" can-remove="vm.items.length > 1" remove="vm.remove(item)"></my-directive>

Then in scope configuration you need to use = binding instead of &:

scope: {
    item: '=',
    canRemove: '=',
    remove: '&'
},

Demo: http://plnkr.co/edit/DlZafON6HEdoyhzvwNIh?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.