Saving attribute values in AngularJS by default

My custom tags use 'repairwidth' with the 'width' attribute to get input. The width is determined by the size.

The first repairwidth tag always has a width of 50.
The second and third repairwidth tags have a dynamic width based on "{{width}}".

I can modify the width using ng-model="width", but setting width="50" directly doesn't seem to work.

Here is a link to a plunker example.

To resolve this issue, I attempted to use scope: {width: '@'}, but for my application, scope must remain false. Unfortunately, I cannot utilize ng-init or ng-model in this scenario.

What am I doing wrong?

<!DOCTYPE html>
<html ng-app="ang" ng-controller="ctrl">
<head>
    <meta charset="utf-8" />
    <title>width with scope: false</title>
</head>
<body>

<b>scope: false</b><br>
    <repairwidth width="50" ></repairwidth> 
    input must have size=50 always 
    <b>Doesn't work</b><br>

    <repairwidth width="{{width}}" ></repairwidth><br>

    <repairwidth width="{{width}}" ></repairwidth><br><br>


 <b>size for 2 & 3 inputs:</b> 
 <input type="text" ng-model="width" />
 I can change size for 2 & 3 inputs
 <b>Doesn't work</b><br>

 <b>not use ng-init and ng-model</b>

 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script>
    var ang = angular.module("ang", []);
    ang.directive('repairwidth', function(){
        return {
          restrict: 'E',
          replace: true,
          transclude: false,
          scope: false,
          template: '<input type="text" size="{{width}}"/>'
            ,
            link: function(scope, element, attrs) {         
                attrs.$observe('width', function(value) {
                    if (value) element.attr('size',value);
                });
            }
        };
    });

    function ctrl($scope) {
        $scope.value= 'text';
    }
</script>
</body>
</html>

Answer №1

When the directive scope is set to false, it means that the directive inherits its scope from the parent. This results in all instances of your directive using the same value for width as set in the controller. Essentially, the width parameter you pass into the directive will be disregarded.

<repairwidth size="{{width}}" ></repairwidth>

is equivalent to

<repairwidth></repairwidth>

The simplest solution is to directly bind to the size parameter like this:

<repairwidth size="50" ></repairwidth> 
<repairwidth size="{{width}}" ></repairwidth>
<repairwidth size="{{width}}" ></repairwidth>

You can even do without the link function.

Check out this Plunker demo.

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

The karma tests may not be passing, but through debugging we can see that

Encountering a puzzling problem with running jasmine unit tests in Karma. One of my unit tests, which relies on an external template (AngularJS directive), fails in Karma but appears to pass when inspected in DEBUG mode within the browser console. Other un ...

Exploring the vertices of a single face of a cube using three.js

My current project involves manipulating the x position of all coordinates on a single face of a cube. Here is my current method: var wDepth = 200; var hDepth = 200; var geo = new THREE.CubeGeometry( 20, 40, 40, 20, wDepth, hDepth); for ( var i = ...

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

Retrieving current element in AngularJS using jQuery

I have 4 templates, each with mouse actions that trigger functions: ng-mouseover="enableDragging()" ng-mouseleave="disableDragging()" Within these functions, I update scope variables and would like to add a class using jQuery without passing any paramete ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Traversing the nested arrays, processing column by column

Below is an array of subarrays const array = [ [0, 1, 2, 3], // Going from top to bottom? [4, 5, 6, 7, 8, 9], // | [10, 11, 12, 13, 14], // | [15, 16, 17, 18, 19], // | ] // V My goal is to achieve the fol ...

Switching from using fs.readFile to fs.createReadStream in Node.js

I have a dilemma regarding my code, which involves reading an image from a directory and sending it to index.html. My goal is to replace fs.readFile with fs.createReadStream, but I am struggling to figure out how to implement this change as I cannot seem ...

Substitute Symbolic Codes in an Object with Written Text

Here's the structure of the object: { where: { [Symbol(or)]: [ [Object], [Object] ] },hooks: true, rejectOnEmpty: false } When I use JSON.stringify on it, the result is: {"where":{},"hooks":true,"rejectOnEmpty":false} T ...

Implementing a click event on an image in an Angular 4 application

I'm facing an issue with adding a click event to an image within an Angular component. I have tried the following code: <img src="../../assets/add.svg" width="18" height="18" (click)="addItem()"> However, this approach does not seem to work as ...

Issue with spacing dropdown choices within primary navigation bar

Struggling with my final project for a class as the semester comes to a close. I've received minimal help from my Professor and hit a roadblock. The main navigation on the side is working correctly, but the dropdown options are stacking on top of each ...

Send a string to directive via HTML

Trying to implement a "clipboard" directive following this example. In my case, I need to dynamically compute the string to be copied to the clipboard. The goal is to pass the output of a function that generates the string to the directive. Currently, I ...

Checking the validity of a JSON file extension using regular expressions

Using EXTJS, I have created a file upload component for uploading files from computer. I need to restrict the uploads to JSON files only and want to display an error for any other file types. Currently, I am able to capture the filename of the imported fil ...

What is the proper way to utilize the equalizer feature within a Foundation modal?

I'm in the process of developing a website using the Foundation library. One of the tasks I'm working on is creating an About "page" for my site using a modal, and trying to make sure that the three different panes inside the modal are equal in s ...

Is it possible to maintain the data types of each individual piece of data when it's divided into an array in

Can the data type of each field be preserved in Javascript after splitting it using the split method? Input: var row = "128, 'FirstName, LastName', null, true, false, null, 'CityName'"; When using the split method, the data type of e ...

Press on the row using jQuery

Instead of using link-button in grid-view to display a popup, I modified the code so that when a user clicks on a row, the popup appears. However, after making this change, nothing happens when I click on a row. Any solutions? $(function () { $('[ ...

Trouble sliding with Material UI Slider

I've encountered an issue with my Material UI slider - it doesn't slide when clicked and dragged. I followed one of the examples on the Material UI website (https://material-ui.com/components/slider/) and included an onChange function. The values ...

Assign a class to a dynamically loaded element on a webpage

As I work on developing my website, I am facing an issue that I need help with. My header is stored in a separate HTML document and it looks like this: <div class="topnav" id="myTopnav"> <a href="Index.html" id=" ...

Turn off the ripple effect for this element

I am looking to turn off the ripple effect on an ion-chip component, which activates when clicked: <ion-chip> <ion-label>Hey</ion-label> </ion-chip> Is there a way to accomplish this? ...

A guide on grouping an entire CSS file under one class umbrella

Is there a way to encapsulate a large number of CSS declarations so they only apply when the parent has a specified class? div { color: #ffffff; } ... a { color: #000000; } Can it be structured like this, with a parent class containing all the CSS r ...

Creating a Parent Container to Maintain the Height of the Tallest Offspring

I've been searching online for solutions, but so far I haven't found one that meets all the requirements. <div class="parent"> <div class="child1">I am 60px tall and always visible; my parent is 100px tall</div> <div ...