Issues with the functionality of the directive's link feature

Today I am diving into the world of directives and came across the compile and link functions. However, I am encountering an issue with my link function that is not working as expected.

Below is my code snippet:

<body ng-app="myModule" ng-controller="myController">
this is  directive<br />
<input id="inputTextColor" ng-model="color" type ="text"/>{{color}}
<br />

<hello> oldertext oldertext </hello>
</body>
<script>
    var myModule = angular.module("myModule", []);
    myModule.directive("hello", function () {
        var directive = {};
        directive.restrict = 'E';
        directive.template = '<b>hi its me <span ng-transclude></span></b>';
        directive.transclude = true;
        directive.compile = function (element, attributes) {
            element.css('border', 'solid 1px black');

            var linkfunction = function ($scope, element, attributes) {
                element.css('background-color', $scope.color);
            }
            return linkfunction;
        }

        return directive;
    });

    myModule.controller("myController", function ($scope) {
        $scope.color = "red";
    });
</script>

My objective here is to dynamically update the background color of my directive based on the text entered in the textbox, since the textbox is bound to my scope.color.

Answer №1

Within the link function, the background color of the element is set based on the scope color whenever the scope color changes. To achieve this, a watch function is necessary:

const linkFunction = ($scope, element, attributes) => {
    $scope.$watch('color', (newValue) => {
        element.css('background-color', $scope.color);  
    });
};

See it in action here: http://example.com/link-function

Alternatively, you can utilize the ng-style directive within the template to handle watches automatically:

directive.template = '<b ng-style="{\'background-color\': color}">Hello there <span ng-transclude></span></b>';

Check out the example here: http://example.com/ng-style-directive

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

Menu with dropdown navigation

Looking to create a dynamic and responsive navbar menu with items and subitems on my website. Bootstrap has proven to be challenging when adding submenus. Are there any tools, frameworks, codes or plugins that could assist me in achieving this? It's ...

Having trouble with AngularJS? Ng-switch not updating after ng-click?

Initially in my code, I check if a user has the ability to flag a discussion. If they do, I use ng-switch where upon flagging, a success message is displayed: <div ng-if="canFlag(discussion)"> <div ng-switch="isFlagging" ng-click="fla ...

Transferring Data from Controller to HTML in AngularJS Version 1

Recently, I started working with angularjs on a new project that involves three main HTML files. The first file is index.html, which contains the ng-view directive. The second file is home.html, where various products are displayed from a database. Each pr ...

Using AngularJS $resource to access JSON data with a root node

As a newcomer to AngularJS, I'm figuring out how to handle server responses from $resource that have a root node. Currently, my approach involves using $resource to retrieve a User object from the backend, similar to this: var User = $resource(&apos ...

Display an HTML icon within a label in an md-tab that uses ng-repeat when selected

I am currently using AngularJS material functionality in my code: <md-tab md-on-select="something" label="{{subsetKey}} ({{subset.data ? subset.data.length : 0;}}) <i class='example icon class'></i>" ng-repeat="(subsetKey, subset) ...

Syncing data with angular-data is a straightforward process that can be easily

I'm currently working on an Angular project that utilizes angular-data to interact with my Restful API. Here's the situation: Within my service, I return a defined resource. In my controller, I use service.defineresource.findAll().then Everyth ...

Display Nvd3 Pie Chart percentages in decimal format

I have integrated Nvd3 into my Angular project to create various types of charts. Utilizing the angular directive from Krispo's website, I am currently working on a pie chart that displays values in percentages. However, the displayed values are round ...

Using AngularJs to create a couchdb document

const post_data = { "task_list": $scope.task_list, "uri": $scope.uri }; $http({ method: 'POST', url: 'http://127.0.0.1:5984/tasklist/' + $scope.task_list, data: post_data }) .success(function(data, status, headers, config) { ...

ngResource is mistakenly handling POST requests as if they were GET requests

It has come to my attention that despite specifying "POST" in my ngResource factory, the parameters are actually being passed as GET. Here's an example of a user factory: myApp.factory('facUser',['$resource', function ($resource) ...

Tips for sending routeparams value to model window in AngularJS

In the current project, I am working on implementing a modal window for the edit screen functionality. The process involves displaying a list of items on the screen, from which users can select one row and then click on the modify button to open the edit s ...

Listener for 'timeupdate' event on video doesn't retain values

My html5 video event listener is designed to pause the video at a specific time while the user participates in a quiz. The first 'lesson' works fine, and the second video also appears to add the listener with the correct pause time. However, when ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

I am experiencing an issue where my REST call is being triggered twice while using AngularJS

Why is my REST call triggering twice when I make the call from the UI? I am using Java v8 and AngularJS v1.6, here is the service: import com.project123.temp.component.ImportFileComponent; @Component @Path("project123/ImportFileService") @JsonIgnorePrope ...

Customizing the appearance of Indicators and Paginator in PrimeNG Carousel

I have integrated a carousel using PrimeNG which has the following design here Take note of the style of the carousel indicators and navigators. I want to achieve the default style of indicators/navigators for the carousel as shown here I have included t ...

Display an error notification when the user fails to provide the necessary quantity of numbers in AngularJS

Hey there, I'm currently diving into the world of AngularJS development and facing some challenges with form validations. I have an input field that should only accept a maximum of 8 digits. My goal is to display an error message if less than or more ...

Flag form field as invalid in AngularJS

Struggling to implement server-side form validation in an AngularJS app? Finding it tricky to invalidate a form field and show an error message? Here's the setup of my app: I have a model 'client' with a controller Accounts.controller(&ap ...

Is it possible for you to generate an array containing only one element?

I've encountered an issue with my code. It functions correctly when the JSON data for "Customers" is in array form. However, if there is only one customer present, the code erroneously creates 11 table columns (corresponding to the number of keys in t ...

Using AngularJS to bind elements within elements

Feel like I might be overlooking a simple solution here, but I'm facing an issue: <h4 ng-bind="example.heading"> <small ng-bind="example.subheading"></small> </h4> This code doesn't seem to work - if ng-bind replaces ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

initiating AngularJS ng-model pipeline on blur event

My $parser function restricts the number of characters a user can enter: var maxLength = attrs['limit'] ? parseInt(attrs['limit']) : 11; function fromUser(inputText) { if (inputText) { if (inputText.length > max ...