Using an expression from the parent controller to disable an item in an AngularJS directive

I created a list of custom directive items, each with a remove button. The issue I'm facing is that I want to disable the remove button when there's only one item left in the list, but it's not working as expected.

To see this problem in action, you can check out my example on Plunker.

It seems like the canRemove: '&' part of my directive might be causing the problem, but I'm unsure how to fix it.

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: As a beginner in Angular, I'm wondering if the way I'm handling item removal is good practice or should I consider using broadcast and on instead?

Answer №1

To start, ensure that your attribute is defined as can-remove:

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

Next, in the scope configuration section, make sure to use = for binding instead of &:

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

Check out a live demo: http://plnkr.co/edit/DlZafON6HEdoyhzvwNIh?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

I keep receiving an error in Angular JS but I'm unsure of the reason

I've been working on AngularJS and created a basic module and controller. I'm attempting to show the data of an element inside the controller on the HTML view page, but all I see is {{student.name}} and I'm receiving an error message that sa ...

Unexpected issue: Angular view is failing to display jade templates

I'm facing an issue while setting up angular with ng-route using JADE. I am unable to connect to my templates where I have stored the HTML files. Below are the steps involved. I know it's a bit lengthy, but I wanted to provide all the details. An ...

Don't forget to expand or collapse

I'm struggling to make this work. My goal is to initially display 50 characters and show the rest when the "read more" button is clicked, and vice versa with "read less." Another problem I've noticed is that when I click the back browser button, ...

Using Axios to facilitate communication between API and Interface

I am facing a challenge in establishing communication between the API and the Interface. To explain further: I send a JSON file from the API, but I am unable to retrieve it and display it in the Interface. The JSON structure is simple: {"name": "joe"} My ...

Create JSX code for rendering components outside of the main component

As someone who is diving into the world of React, I am currently on lecture 23 out of 247 on Udemy where I am learning about states and events. However, one particular question has been lingering in my mind without a definitive answer. Our company has mad ...

Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total pric ...

What is the best way to customize the styles of a reusable component in Angular2?

I am working with a reusable component called "two-column-layout-wrapper" that has its styles defined in the main .css file. In another module, I need to use this component but customize the width of two classes. How can I override these styles? import ...

Exploring the power of searching JSON data using ReactJS

After reading through the "Thinking in React" blog, I'm inspired to create something similar. Instead of filtering an array table, I want it to display the row that matches the input value. I have attempted this and created a jsfiddle example here: j ...

Enable autocomplete feature in a PHP form once the user starts typing their name

After searching for similar questions, I couldn't find any with the same "variables," so here's my dilemma: I have a basic form where I input a name and I want the rest of the form to be filled in automatically (ID). Retrieving data from the da ...

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

Interacting with dynamically loaded HTML content within a div is restricted

On my main HTML page, I have implemented a functionality that allows loading other HTML pages into a specific div using jQuery. The code snippet looks like this: $('.controlPanelTab').click(function() { $(this).addClass('active').s ...

Having difficulty managing asynchronous functions with the useState hook in React

import React from "react"; import { UserContext } from "./../contexts"; import { removeStoredAuthData, storedAuthIsValid, storeNewAuthData, } from "./../utils/auth"; import { getUserInfos } from "./../api/userAuthen ...

AngularJS ng-include nested form configuration

My application utilizes nested ng-includes. The outer include is a login screen for one application while the inner ng-include includes two templates. The login screen is designed in two steps where the email is checked first and then the password entered. ...

The value of req.body.name cannot be determined in Express using Node.js

I want to implement a like/dislike feature on my website using HTML and JavaScript. Here is the code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> <input type="submit" name="vote" value= ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Thorax.js bower installation issue

After following the instructions in this guide: https://github.com/walmartlabs/thorax-seed/blob/master/README.md, I ran into an unexpected issue on my Windows machine. When running npm start It seems like bower is doing a lot of work (presumably loading ...

What is the best way to conceal the standard 'X' close button within a magnific popup interface?

I implemented the Magnific-popup plugin in my jsp to show messages to users. Here is the code I used to open Magnific Popup: $.magnificPopup.open({ items: { type: 'inline', src: '#idOfSomeDivInPage' }, focus: '#some ...

Watching a service's attribute from within a route in the EmberJS framework

There seems to be a concept that I'm struggling to grasp here. To my understanding, any instance of Ember.object should be able to observe properties on another instance of Ember.object. In my scenario, there is a service, a router, and a component i ...

Utilize the 'Save and add another' feature within a bootstrap modal

Hello everyone, this is my first time seeking assistance on this platform. If any additional information is required, please do not hesitate to ask. Currently, I am working with JavaScript in combination with the handlebars framework. Within a bootstrap ...