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

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

Converting a timestamp to a date format within AngularJS interpolation

Is there a way to send a timestamp, such as 1519357500, to HTML and then convert it into a date format while using interpolation? I attempted the following approach but unfortunately it did not work: {{moment($ctrl.myTimestamp).format('MMMM Do YYYY, ...

Error in JSON parsing: Unexpected token 'u' at the beginning of the input in Angular2

I attempted to create a server using dummy data. Below is the System.js Config I have implemented (given that my routing is slightly different, this setup has been working well so far) System.config({ // baseURL to node_modules b ...

Unable to activate function in controller from AngularJS directive

I'm having trouble getting a function in my controller to run after the inplace edit in order to update my data. I can't figure out why it's not triggering... How can I verify that I'm in the correct scope? My framework is Meanjs As a ...

The issue of video tags not displaying previews on iPhone across all browsers is also accompanied by problems with controls not functioning correctly

As I delve into the world of HTML5 video tags, I encountered an issue where the video wouldn't show a preview frame initially. Instead, only the Resume button would appear. Furthermore, after playing the video with the Resume button, it wouldn't ...

Error: Collection2 validation did not pass: The field 'name' must be filled in, the field 'email' cannot be empty, and the field 'message' is mandatory

I need to set up a way for visitors to send messages through my website const mongoose = require("mongoose"); mongoose.connect("MongoDb-Connection-Uri") .then(() => { console.log("mongodb connected"); }) .catch(() => { console.log("fail ...

What is the best way to handle sequential $http calls in AngularJS? Specifically, I want to make the second $http call dependent on the response of the first

When making two $http calls, the second call should only be executed based on the response from the first call if there is an error present. ...

Struggling to eliminate buttons upon clicking, but they persistently reappear (JavaScript, HTML)

I have encountered an issue with buttons in my table that I am struggling to resolve. Each row in the table contains a "Pack" action button, which when clicked, is removed to prevent accidental double-packing of items. Everything was functioning smoothly ...

Updating the fixed value and sending it to subordinate controllers in Angular version 1.4.9

I'm facing an issue with updating the value of a constant from the root controller. When the state transitions to a login controller, the constant still holds the old value. The CONSTANT is initially defined like this: var myApp = angular.module("ap ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Menu options are unresponsive to clicks in the dropdown

Need help fixing my dropdown menu issue. Whenever I hover over the dropdown, it disappears before I can click on any items. Here is a snippet of the code causing the problem: #navContainer { margin: 0; padding: 0; padding-top: 17px; width: 220 ...

Creating a custom arrow design for a select input field using CSS

I'm currently developing a website (using Wordpress with a custom theme) and I want to incorporate an up/down arrow in the select input field using CSS. The HTML code I have for creating the up/down arrow in the select input field is as follows: < ...

Ways to dynamically assign a class to a single element within a group of identical elements

I have three identical items in the DOM. Specifically, I am referring to a moving line <span class="caret"></span> <ul> <li class="nav-item-1"> <a href="#">ITEM 1</a> <span class="caret"></span> ...

Convert the list items into JSON format

<div class="col-xs-4 no-padding contenteditable-color" style="background-color: transparent;"> <ul class="ul-product"> <li class="li-product-page cars contenteditable" contenteditable="false">qweryt</li> </ul&g ...

Transmitting data as an array using JQuery

$('[data-toggle="mftapproveCheck"]').click(function () { var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get(); //alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") ...

jQuery is missing an essential component that is causing an error

I have successfully implemented the following JavaScript code and everything is working fine. However, I'm uncertain if my code is fully correct. I noticed that in my script, I only utilize success: function() without incorporating an error function. ...

Show a pair of pictures every X hours using Javascript

Trying to create a code that displays different pairs of images each day, but struggling to make it select them randomly. Instead, the code currently just goes through the array one by one. I'm not great with Javascript and haven't found a way to ...

Executing ng-click to access outer controller from within nested ng-controllers

I'm exploring the potential of using angularjs to develop a dynamic page with the following capabilities: It starts off blank, except for a dropdownlist that automatically populates with various apps. Upon selecting an app from the list, relevant da ...

What is the proper method for securing this?

Trying to retrieve 'this' within a method that is invoked by pressing a button, where this points to both the class and the pressed button: p.myVar = 'apple'; $('.go').on('click', this._init); p._init = function(e ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...