Modifying attribute values in Angular through custom directives

Struggling to figure out the most efficient way to monitor attribute changes, preferably triggered by a keypress event and linked to the scope in the parent controller

I want each individual instance of the directive to have its own 'hasFocus' property that can be modified by updating the attribute value e.g.

<menu has-focus="{{ true }}" ></menu>
<menu has-focus="{{ false }}" ></menu>
<menu has-focus="{{ false }}" ></menu>

template:

<div class="menu">
<ul>
    <li ng-repeat="option in menu.options" ng-class="{ 'focused' : hasFocus  }" tabindex="{{ $index }}">
        <div class="icon">{{ $index+1 }}</div>
    </li>
</ul>

and therefore, only one directive should have the attribute value set to 'true' at any given moment.

I've created a custom directive

.directive('menu', function()
{
  restrict: 'E',
  templateUrl: 'partials/menu-left.html',
  replace: true,
  scope: {
        hasFocus: '@'
  },
  link: function($scope, element, attrs)
  {
    attrs.$observe('hasFocus', function(value) {
        console.log(value);
     });
  }

}) 

but I'm having trouble extracting the value from the $observe method I tried using $watch but it didn't work either. Not sure what I'm missing!

Answer №1

In the event that you utilize the @ binding, there may be a necessity to implement $watch in this manner:

$scope.$watch(function(){
   return attrs.hasFocus;
}, function(val) {
     $scope.hasFocus = val;
});

If this approach proves ineffective, or if you lean towards two-way binding using =:

<menu has-focus="true" ></menu>

and

.directive('menu', function()
{
  restrict : 'E',
  templateUrl : 'partials/menu-left.html',
  replace : true,
  scope : {
        hasFocus : '='
  },
  link : function( $scope, element, attrs )
  {
    // $scope.hasFocus contains true/false
  }

}) 

I personally believe that two-way binding is superior, particularly with boolean values, because if your intention is merely to dictate the appearance of the DOM, monitoring for changes might not even be necessary. You could simply insert $scope.hasFocus into the DOM (via ng-show, ng-switch, etc.)

EDIT: It just occurred to me that given your template, utilizing two-way binding (=) eliminates the need for watching.

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

Error exporting a function in Node.js

As someone who is new to writing node.js modules, I have been working on a module in the following way, a.js var fs = require("fs") ; var util = require("util") ; var mime = require("mime") ; module.exports = { getDataUri: function (image, callback ) ...

Issue with background opacity not functioning properly in Internet Explorer 8

I am facing an issue with displaying 2 images in IE8 and IE9. Below is the code snippet causing the problem: .ui-widget-content { border: 0px solid #aaaaaa/*{borderColorContent}*/; background: rgba(0, 0, 0, 0.1) ; /*{bgColorContent}*/ url(images ...

Creating dynamically generated nested text inputs with individual v-model bindings upon the clicking of a button

As a newcomer to vuejs, I am attempting to create nested textboxes dynamically with the click of a button. For a clearer explanation, please refer to this jsfiddle link: https://jsfiddle.net/avi_02/qLqvbjvx/ Let's use an analogy to grasp the iss ...

Issue with Loading Data on AJAX Causing Scrolling Difficulties

Currently, I am in the midst of website development using PHP, MySQL, and JavaScript (JQuery + Ajax). One issue that has arisen is with the customer scroll function and scrollbars. When loading data via ajax, the scroll function is generating numerous erro ...

Retrieve an item from an array using AJAX

I am working on a function using ajax that retrieves a set of values: $.each(data.dataa, function (i,item) { $.each(item, function (index, dat) { $str+=dat; }) $ulSub.append( '<li id="'+item.id +'" class="ui-widget-c ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...

Exploring the synergies of Next.js and Node.js thread pooling

In my current project, I am utilizing nextJS with NodeJS and looking to implement child processes or workers. The code provided by NextJS itself is functioning perfectly. The relevant code snippets: NextJS with NodeJS Another resource I referred to: Nex ...

Utilizing Google Chrome Extension: Sharing variables between injected scripts via chrome.tabs.executeScript to another script injected in a similar manner

Can anyone help me with a coding challenge? I have two scripts injected in my popup.js and I need to make a variable defined in one script accessible to the other. Here's how I'm injecting the scripts: let sortFunction = function (goSortParam) { ...

[Babel]: The option foreign.Children is not recognized

I encountered an error while building with the following script: webpack --colors --progress --watch --config --jsx-loader webpack.config.js Below is the content of my package.json file: { "dependencies": { // List of dependencies here }, "dev ...

Pressing the Button Increases the Counter, However the Counter Resets After

My goal is to create a basic counter with increment and reset buttons. When I click on the increment button, the counter properly goes from 0 to 1 (I can confirm this by checking the console log in Chrome). The issue arises when, after incrementing, the c ...

Tips for creating a function to assign a CSS width using a JavaScript variable?

Here is the code snippet I have been working on: ...<script> function adjustElementSize() { var newSize = window.innerWidth - 600; document.getElementById("spin").style.width = newSize + "px"; document.getElementById("spin").style.height = newSize + ...

Issues with React and Recharts legend functionality causing disruptions

I am currently experimenting with React and Recharts to build a stacked and grouped bar chart. This is my first experience using Recharts, and I have encountered an issue with the legend functionality. I would like the legend to toggle both graphs within e ...

submitting image data from HTML5 canvas using an HTML post request

I am having issues sending canvas data to the server side as an image. Despite making an HTTP post request, I am unable to retrieve the data on the server side. $_POST remains empty, even though I can see the image data when console logging the object on t ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...

Replicate all Column Cell Input Values using the value of the first Cell in the Column as a

Is there a way to copy the input value from the first cell of a specific column in an HTML table, and paste that value into the remaining cells of that column? Essentially, the user would enter a value in the first cell, then by clicking a button, that v ...

Using node.js to send custom data over a websocket

I came across an excellent tutorial on websockets. In this tutorial, the server decodes and writes a message to the console whenever it receives a message from the client. After that, the server sends the message back to the client. var firstByte = data ...

Change the position of an HTML image when the window size is adjusted

My web page features a striking design with a white background and a tilted black line cutting across. The main attraction is an image of a red ball that I want to stay perfectly aligned with the line as the window is resized, just like in the provided gif ...

Use RxJS chaining to transform an observable of `File` objects into an observable of strings encoded in base64

I have successfully written code that converts my File object to base64: let reader = new FileReader(); reader.readAsDataURL(myFile); reader.onload = () => { let resultStrOrArrayBuf = reader.result; if (!(resultStrOrArrayBuf ...

Having difficulty interpreting the json data retrieved from the specified url

<html> <body> <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script> <script> $(document).ready(function () { $.ajax({ type: 'GET& ...