What is the best way to access external value in an Angular directive?

check out this plunker link.
HTML:

<body ng-app="app">
    <h1>selectable</h1>
    <selectable text="link1" status="true"></selectable>
    <selectable text="link2" status="false"></selectable>
    <p>
      link1 is <!--status of link1, true or false-->
    </p>
    <p>
      link2 is <!--status of link2, true or false-->
    </p>
  </body>

JS:

angular.module("app", [])
.directive("selectable", function(){
  return {
    restrict: "AE",
    replace: true,
    scope: {
      status: "=",
      text: "@"
    },
    link: function(scope, ele, attr){
      ele.on("click", function(){
        scope.status = !scope.status;
        scope.$apply();
      });
    },
    templateUrl: "./tmpl.html"
  }
})

template:

<span class='myLink' ng-class='{"active": status, "": !status}'>
  {{text}}
  {{status}}
</span>

Is there a way to retrieve the current status of both link1 and link2 and display them?
Appreciate any help!

Answer №1

Implement the ng-controller directive to control functionality

<body ng-app="app" ng-controller="MainCtrl">

Within the MainCtrl function, define two variables to represent the status of two links as follows:

.controller('MainCtrl', function($scope) {
    $scope.link_1_status = true;
    $scope.link_2_status = false;
})

Bind these variables to the status variable of the directive scope like this:

<selectable text="link1" status="link_1_status"></selectable>
<selectable text="link2" status="link_2_status"></selectable>

Print out the status using the following code:

<p>
    link1 is {{link1Bool}}
</p>
<p>
    link2 is {{link2Bool}}
</p>

Here is a link to the PLUNKER page

Alternatively, if you prefer not to use ng-controller, you can utilize ng-init instead.

<body ng-app="app" ng-init="link_1_status = true; link_2_status = false">
....
    <selectable text="link1" status="link_1_status"></selectable>
    <selectable text="link2" status="link_2_status"></selectable>    
....
</body>

Here is a link to the PLUNKER page

Reasoning Behind This Approach

If you simply use

<selectable text="link1" status="true"></selectable>
, you are assigning the value true directly to the directive scope's status variable. While it will toggle the value when clicked, you won't be able to access that value because there is no reference to it (you're passing just a raw value without any reference or identifier). Thus, having references like link_1_status and link_2_status allows you to access and manipulate the properties effectively.

Answer №2

Check out the code sample I provided.

In my opinion, utilizing a controller is the correct approach for sharing data between your form and adding some logic to manage that data.

<body ng-app="app" ng-controller="ctrl">
<h1>selectable</h1>
<selectable text="link1" status="firstStatus"></selectable>
<selectable text="link2" status="secondStatus"></selectable>
<p>
  link1 is {{firstStatus}}
</p>
<p>
  link2 is {{secondStatus}}
</p>
</body>

Here is an example of the basic controller code:

.controller("ctrl", function($scope){
  $scope.firstStatus = true;
  $scope.secondStatus = false;
})

Answer №3

Make sure to store that value in a scope variable and then pass it to the directive attribute. Since you are already using = for two-way binding in Angular, the magic of binding will be displayed. If the value passed to the isolated directive changes, it will also change the underlying value in the scope from where it was passed and vice versa.

Code Example:

<body ng-app="myApp">
    <h1>Selectable Options</h1>
    <selectable text="link1" status="link1Bool"></selectable>
    <selectable text="link2" status="link2Bool"></selectable>
    <p>
      The status of link1 is {{link1Bool}}
    </p>
    <p>
      The status of link2 is {{link2Bool}}
    </p>
</body>

View Demo Here

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

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Node.js data transmission: Sending information from server to client

In my node project, PUG/Jade files are used to render webpages. Every minute, a JS file updates a redis database and I want the GUI to reflect these changes without requiring a page refresh. Here is an overview of how the data is currently passed: User ...

Using ajax to submit a request to the controller

I'm currently developing an ASP.NET Core MVC application and have a registration page set up. My goal is to return View with errors if the model state is false: @model WebApplication2PROP.Entities.UserRegister @* For more information on enabling M ...

Node.js NPM Google search results showing [ Object object ] instead of actual result

searchOnGoogle: function(searchQuery){ googleSearch.query({ q: searchQuery }, function(error, response) { console.log(response); botChat.send ...

Interact with embedded elements in JavaScript by using the onClick event

Here is a JavaScript code snippet I've been working on: <div> <tr onClick="click1()"> <td> click 1 </td> <td onClick="click2()"> click 2 < ...

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Navigate using Ui-Router or else utilize ng-admin

Currently, I am facing an issue in my angular application. I have integrated ng-admin to create a simple admin panel and also included Authentication features. My goal is to redirect the user to a login state when there is no active session. Upon integrat ...

What is the best way to send the index of an array to a onClick event in ReactJS?

const DisplayInventory = ({ items }) => <div className="row"> {items.map((item, i) => <div className="item" key={"item_" + i}> <div className="card hoverable col s3"> <img onClick={purchase ...

What steps can I take to determine the status of my Axios post request?

Here's a simple task I'd like to accomplish using Axios for an Ajax request. When a user clicks on a button, I want to fire an Ajax request. While the request is processing or until it's completed, I would like to disable the button or impl ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

Ways to create a back-and-forth transition across a sequence

Is it possible to create an animation that changes the width of an element once, then reverts back after a pause? I want this transition to occur over a three-second interval followed by a two-second delay. How can I achieve this? Below is the code I have ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

How can I extract the text enclosed in <li> tags using JavaScript?

Can someone help me with retrieving the text content of li tags? I managed to get a list of lis, but I'm having trouble assigning the text content to my country object. Snippet var lis = document.getElementById("navbar").getElementsByTagName("l ...

Elevating State in React Architecture

Recently, I delved into the React documentation on lifting state up and found this helpful resource. In one of my projects, I encountered a similar issue with a slight twist. Instead of dealing with <TemperatureInput />, I had to work with <Senso ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

What is the best way to fetch multiple values using momentjs from firebase?

After fetching data from Firebase and storing it in an array, I am attempting to retrieve the posted_at values (timestamp of when something was posted) in a time format using Vuejs. However, I am facing difficulty as it only retrieves a single value instea ...

React Redux components are failing to render after changes are made to the state array

I'm fairly new to using React, Redux, and Thunk in my project. Right now, I'm facing an issue where I fetch an array from an API call in my action/reducer, but it doesn't re-render in the connected component/container that's hooked up t ...

Selecting an option from dropdown1 to retrieve a specific value from a JSON file

I currently have 2 dropdown lists to fill with data from a JSON file: $scope.categories = [ {name:"Blouse", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Shirt", sizes:["36","38","40","42","44","46","48","50"]}, {name:"Pants", size ...

Unable to open a modal in Angular UI after closing the initial modal

Hey there! I've been attempting to open a modal after closing the first one, but I'm encountering an issue where the second modal appears to be opened but is actually not. I'm struggling to understand what's causing this problem. Could ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...