AngularJS directive with isolated scope

As a beginner in Angular, I am trying to create my own directive to understand how these objects function. My main challenge lies in isolating the scope of the directive so that I can use it multiple times within the same controller.

To illustrate the situation better, I have created a plunker: http://plnkr.co/edit/NsISESR9sIs5Nf577DX4?p=preview

Here is the example code:

<body ng-controller="MainCtrl">
  <button id="button1" ng-click="dummyClickFoo()" wait-button>Foo</button>
  <button id="button2" ng-click="dummyClickBar()" wait-button>Bar</button>
</body>

And the JavaScript code:

app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
    $scope.dummyClickFoo = function() {
        $scope.startSpinner();

        setTimeout(function() {
                $scope.stopSpinner();
          }, 3000);
    };

    $scope.dummyClickBar = function() {
        $scope.startSpinner();

        setTimeout(function() {
                $scope.stopSpinner();
          }, 3000);
    };
});


app.directive('waitButton', function() {
    return {
        restrict: 'A',
        controller: ['$scope', '$element', function($scope, $element) {
            $scope.startSpinner = function() {
                alert($element.attr('id'));
            };

            $scope.stopSpinner = function() {
                alert($element.attr('id'));
            };
        }]
    };
});

While this setup works with one button, it encounters issues with two buttons. I understand the need to isolate their scopes but I am unsure of how to do so without using extra attributes to pass variables. Most examples I've found online rely on passing variables, whereas I need to call internal methods.

If anyone can guide me on how to achieve this, I would greatly appreciate it. Thank you!

Answer №1

To establish an isolated scope within your directive, simply include scope: {} in the directive definition.

It is important to note that once you create an isolate scope, calling startSpinner and stopSpinner from your controller will no longer be possible – nor advisable! Instead, utilize ng-click within your directive or bind the click handler directly within the directive itself. Assuming your directive lacks markup, it is recommended to opt for the latter approach:

// Incorporate this after defining the directive's controller
link: function(scope, element) {
   element.on("click", function() { scope.startSpinner() });
}

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

Verify whether the field includes a minimum number of numerical digits

I am currently using this script to validate whether a field is empty or not. The script works well for me, but I would like to add a condition that the field must contain at least 10 digits (numbers). If it doesn't meet this requirement, I want to di ...

Creating a "Mark as Read" function using localStorage

Looking for a solution to persist the state of "Mark as Read" or "Mark as Unread" even after refreshing the page? Want to use localStorage to save this data? Here's an example of code snippet for toggling between these states: function readunread() { ...

Leveraging Laravel Blade and Ajax for lightning-fast searching

Here is my jquery code When running the code, I encountered an issue where Laravel blade did not recognize the $results variable in the foreach statement. Despite the fact that I did not provide the form or route code, they function as expected. The main ...

Navigate to the element by clicking on the link, then apply a class to that specific element

I'm currently working with this HTML code: <div id="main"> <p>some text</p> <a id="goto-notes" href="#">see notes</a> <p>some text...</p> <div id="notes"> <p>notes here< ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

A guide on dynamically using jQuery to embed an image within a hyperlink tag

I am having trouble with these HTML tags: img = <img data-dz-thumbnail="" target="_blank" alt="twitter-btn-mob.png" src="image.jpg"> a = <a href="javascript:void(0)" target="_blank"></a> My goal is to insert the image tag into the anc ...

What is the reason that jQuery does not work on HTML generated by JavaScript?

One of my JavaScript functions, named getImages, is responsible for loading the following HTML structure: // Function starts here function getImages() { $.getJSON(GETIMAGELIST, function(data) { var items = []; // Populating the HTML $.each(dat ...

Managing events inside a JQuery dialog box

Currently, I have successfully implemented a JQuery dialog that allows users to change their password. The functionality works smoothly as the system checks if the two passwords match and if the new password meets the minimum requirements before making an ...

Display collection in Vue app

I am working with a model called files, which includes a property named response containing an array called errorMessages. In my Vue component, I am looking for a way to display these errors individually rather than as an array. Is there a solution for thi ...

Triggering a page refresh with Framework7

Currently, I am in the process of developing a compact webapp utilizing the framework7 split-view-panel example. This eases navigation by providing a left-hand navigation bar that, upon clicking, loads a URL in the right-hand panel. However, I have notice ...

Utilizing d3.js to implement a scatterplot with zoom functionality that focuses solely on zooming the axis without affecting

Having trouble creating a scatterplot with zoom functionality where only the axis is getting zoomed, not the data itself. Can anyone provide some assistance or insight on what might be wrong? If you're interested in checking out the project, here&apo ...

Trouble viewing Geojson map on website

I'm having trouble generating a map. I am currently working with one of the geojson files provided by The New York Times ("census_tracts_2010.geojson") from this link ( https://github.com/dwillis/nyc-maps ). If someone could take a look at my code be ...

What could be causing the malfunction of this setTimeout function? Another related question to consider

I recently implemented a script on one of my pages, but I noticed that the setTimeout function doesn't seem to be triggering. Currently, it's just set up to display an alert as a test. I suspect that the issue might be related to a meta refresh t ...

JavaScript Function that Automatically Redirects User or Updates Text upon Clicking "Submit" Button

Looking to create JavaScript functionality that directs users back to the homepage after submitting their name and email. The process should follow these steps: 1.) User clicks "Request a Brochure..." https://i.sstatic.net/KqH2G.jpg 2.) A window opens in ...

Implement jQuery to close multiple div elements

My dilemma involves a series of divs with different manufacturer IDs listed as follows: manufacturer[1], manufacturer[2], manufacturer[3], ... etc ... In attempting to create a JavaScript for loop to hide each div, I discovered that it was not achievab ...

Tips for preventing 'Index out of Bound' errors when working with Protractor ElementArrayFinder

I'm completely new to Protractor and I've just started using it in combination with chai and chai-as-promised. Right now, I'm trying to find the best approach for handling a situation where my ElementArrayFinder doesn't contain the elem ...

Is there a way for me to choose the item from the search dropdown so that it fills in the search input field automatically?

Upon typing a word into the search input field, a list of suggestions will appear below. https://i.sstatic.net/etOBI.png Is there a way for me to select a word from the list like Maine (ME) and have it automatically fill the search input field? What chan ...

jQuery click event handler performing no action

I am encountering an issue with the input on my index page: <input type="button" name="goReplaceAll" value="Go" id="allReplaceGo" style="cursor:hand;" /> There is an onclick call from jQuery as follows: $(document).ready(function() { $(&ap ...

elasticsearch query for deletion only returns documents that are not found

I have been attempting to use the https://www.npmjs.com/package/elasticsearch-deletebyquery package to delete documents using a query. However, I keep receiving a "Not found" error. Here is my code snippet: client.deleteByQuery({ index: index, type: t ...

Exploring Javascript object properties in an array and matching them against a specific value

Can someone provide a clear explanation of my question using an example? I have an array of objects structured like this: [{a:"a",b:"",c:"c"}, {a:"a",b:"b",c:""}, {a:"",b:"b" ...