The directive binding value is accurate, however it is failing to return a true result

The behavior of a custom directive is puzzling me. When I directly pass in a value, it works fine. However, if I bind the value to a variable, it doesn't work as expected. Interestingly, when I use console.log to show the value, it appears to be correct but does not return true.

//directive
angular.module('tallllyApp')
  .directive('userColor', ['simpleLogin', '$timeout', function (simpleLogin, $timeout) {
    'use strict';
    return {
      restrict: 'AE',
      scope: {
        color: '@'
      },
      link: function(scope, el, attrs) {
        el.css('background', '#5DC472');
        console.log(attrs); //attrs.color shows 'Andrey'
        console.log(attrs.color); //displays nothing
        console.log(attrs.color === 'Andrey'); //false
      }
    };
  }]);

//html = {{profile.name}} does output 'Andrey'    
<section class="col user-tasks" user-color color="{{profile.name}}">

Answer №1

It's possible that the issue you are experiencing is related to the asynchronous nature of the assigned profile.name. It could be that the data is not yet available when the directive is executed. One approach to address this is to wait for the data to be retrieved by setting up a watch on the attribute (attrs.$observe) or the scope property (scope.$watch), and then remove the watch once the value is obtained.

Here is an example:

  link: function(scope, el, attrs) {
        el.css('background', '#5DC472');

       //attrs.$observe('color', function(v){
        var unWatch = scope.$watch('color', function(v){ //Set up a watch
          if(v){ //Check if the value is available
            unWatch(); //Clear the watch
            initializeDirective(); //Initialize the directive
          }
        });

        function initializeDirective(){
           console.log(attrs);
           console.log(scope.color); //attrs.color
           console.log(scope.color === 'Andrey');
        }
      }

Check out this Plnkr example

Answer №2

Have you experimented with binding the scope in a different way, such as shown below? (Although in my case, both methods worked)

//directive
angular.module('tallllyApp')
  .directive('userColor', ['simpleLogin', '$timeout', function (simpleLogin, $timeout) {
    'use strict';
    return {
      restrict: 'AE',
      scope: {
        color: '='
      },
      link: function(scope, el, attrs) {
        el.css('background', '#5DC472');
        console.log(scope.color); //should display 'Andrey'
      }
    };
  }]);

//html = {{profile.name}} does output 'Andrey'    
<section class="col user-tasks" user-color color="profile.name">

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

Storing data with NPM global packages: Best practices

I have developed a global npm package that functions as a CLI tool. https://i.sstatic.net/PdT3Z.png My goal is to customize the user experience by having the package remember the user's previous choices. For example, if the user selects 'Iphone ...

Steps for updating object state in React

Here is the code snippet that I am working with: this.state = { user: null } I am trying to figure out how to set the name property of the user when it exists. Unfortunately, using this syntax this.setState({user.name: 'Bob') doesn't ...

Error encountered while attempting to cast value "xxxxxx" to ObjectId in the "item" model, resulting in a CastError

I've been struggling to resolve an error while trying to delete a todo from a page using findByIdAndRemove and findByIdAndDelete methods. Despite researching and attempting various solutions, the error persists. Any assistance would be greatly appreci ...

AngularJS Reverse Geocoding Explained

I've been working on implementing reverse geocoding functionality in my Angular project, but so far I've only been able to extract the latitude and longitude coordinates from a location. Unfortunately, every time I try to use the reverse geocodin ...

Generating a checkbox grid by utilizing ng-repeat

Given the Json structure provided below, [ { "name": "module1", "categories": [ { "name": "cat1" }, { "name": "cat4" } ] }, { "nam ...

Responsive design element order rearrangement

My code example is as follows: <div class="info-container"> <span class="item1">item1</span> <a class="item2" href="#">item2</a> <a class="item3" href="#">item3</a> </div> I want to rearran ...

Guide on retrieving file information after transmitting it to another PHP file through Ajax

I have written code to upload a file and send it to a php page. I would like the response to be an array containing information about the uploaded file such as name, size, type, etc. I am using the "POST" method for uploading the file. Is this approach cor ...

Monitoring changes in input can be a crucial step in any data analysis

Is there a way to track changes in input using backbone? How it can be achieved in AngularJs: <div ng-controller="W3"> <input type="text" ng-model="val" > <p>{{val}}</p> </div> I would like the value of the in ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

What are the steps to sorting in JavaScript?

I need help with sorting an array. The array I have looks like this: var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}] I've tried to sort it using the following code: temp.sort(function(a){ a.rank}) But unfortun ...

Recurring Triggering of Angular Directive

As a newcomer to AngularJS, I am facing an issue with my custom directive called sizeWatcher. This directive, when placed as an attribute in the HTML, is supposed to retrieve the height of the element it's attached to and store that height in a scope ...

Extracting values from PHP using AJAX

Whenever a user clicks on the download button, a zip file is successfully created on the server with the necessary files. However, instead of getting an alert with the location of the zip variable ($zip) from PHP as expected, it shows [object Object]. The ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

Cypress is having trouble loading a particular URL

I'm encountering a timeout error while trying to load a specific URL using Cypress. Even after setting the page load time to 2 minutes, the issue persists. Interestingly, general URLs like https://www.google.co.nz/ load without any problems. it(' ...

Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removi ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Output PHP variable in JavaScript (and show the value within an iframe)

I'm trying to retrieve a value from a MySQL database using PHP, store it in a variable, output the PHP variable in JavaScript, and then display the value in an iframe. However, I'm having some trouble getting it to work... Here is my PHP code: ...

What changes do I need to make in order for this code to be compatible with Google Sites?

I am working on creating a random redirect button and need to modify the code below in two ways: <script> <!-- /* Random redirect button- From JavaScript Kit (http://javascriptkit.com) Hundreds of scripts available for free! Please keep this cred ...

How to customize a dropdown menu with the size property?

Can anyone help me with styling a select box that uses the size attribute? Most tutorials only cover single-item select boxes. Has anyone dealt with styling select boxes with the size attribute before? Here's an example of what I'm trying to acc ...