The functionality of AngularJS ng-model seems to be disrupted when it is set within a directive

Is it possible to automatically generate the ng-model of an input based on the name of the input itself? This requirement arises from using Html.TextBoxFor in MVC, which creates the necessary name for binding the input to the server-side model. To streamline the process and minimize user error, I would like my team to simply add a directive that handles this automatically. I came across this code snippet on stackoverflow to achieve this.

datatableApp.directive('automaticangularmodelbinding', function ($compile) {
            return {
                restrict: 'A',
                replace: false,
                priority: 10000,
                terminal: true, // setting terminal to true and giving it a high priority will prevent other directives from running initially
                scope: {
                    automaticangularmodelbinding: '@@'
                },
                link: function (scope, element, attrs) {                    
                    attrs.$set('ngModel', (scope.automaticangularmodelbinding != '') ? (scope.automaticangularmodelbinding + '.' + attrs.name) : attrs.name); // set the value of ng-model to match the name attribute
                    attrs.$set('automaticangularmodelbinding', null); // remove the directive to prevent recursion

                    $compile(element)(scope); // start compiling other directives
                }
            };
        });

This implementation successfully creates the ng-model with the element's name. However, when retrieving data from the server and populating the inputs, the values don't show up. If I remove the automatic directive and define ng-model manually, it works as expected.

The code snippet for fetching data from the server:

$scope.getEditStreet = function (streetID) {
                $http.post('@Url.Action(Model.GetFormControllerFunctionName, Model.GetFormControllerName)', "{ @Model.JavascriptEditPropertyName : " + streetID + "}").then(function (response) {                    
                    $scope.editFormData = response.data.ResultObject;
                    $scope.$apply();                        
                }, function (response) {
                    alert("fail" + response.statusText);
                });
            };

Initially, using ng-model required calling scope.apply to update checkboxes. But after switching to the automatic approach, scope.apply throws errors. Even without scope.apply, the text boxes don't populate, despite working fine before.

It appears that adding ng-model dynamically after the fact is causing issues compared to having it defined from the beginning. How can this be resolved?

Edit:

After considering zaitsman's comments, the revised version that functions properly is as follows. I removed scope from the directive and utilized attrs['automaticangularmodelbinding'] for passing the necessary data.

datatableApp.directive('automaticangularmodelbinding', function ($compile) {
            return {
                restrict: 'A',
                replace: false,
                priority: 10000,
                terminal: true, // setting terminal to true and giving it a high priority will stop other directives from running initially
                link: function (scope, element, attrs) {                    
                    attrs.$set('ngModel', (attrs['automaticangularmodelbinding'] != '') ? (attrs['automaticangularmodelbinding'] + '.' + attrs.name) : attrs.name); // set the value of ng-model to match the name attribute
                    attrs.$set('automaticangularmodelbinding', null); // remove the directive to avoid recursion

                    $compile(element)(scope); // begin compiling other directives
                }
            };
        });

Answer №1

After our discussion, I recommend skipping isolated scope to allow for the use of variables from the directive's declaring scope. To access the values passed to the directive, make use of the attrs object.

To do this, simply remove scope from the directive entirely. Then, within the link function, you can retrieve the value like so:

var myPara = scope[attrs['automaticangularmodelbinding']];

This will give you access to extraParameterInFront from the parent scope. If the parameter is just a string, obtaining it becomes even simpler:

var myPara = attrs['automaticangularmodelbinding'];

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

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

Changing JavaScript functions into jQuery functions

Currently, I have this Javascript function that I am interested in converting to jQuery: function confirm() { var http = new XMLHttpRequest(); var url = "index.php?tag=' . $dt . '"; var params = "confirm_ref=' . urlencode(encry ...

jQuery UI Autocomplete for web addresses

I am trying to implement instant search with jQuery UI autocomplete, and I want to be able to add a link that will be triggered when a result is clicked. Javascript $("#searchinput").autocomplete({ source: "search/get_searchdata", select:function ...

Tips for aligning meshes to the left and ensuring responsiveness in three.js

Currently working on a website using three.js, I'm facing an issue where I can't seem to align and make the mesh responsive simultaneously. My current approach to alignment is: cube.position.x = -20 However, when I try resizing the window, the m ...

Instead of returning a JSON result, the MVC controller method called from AngularJS is returning the view HTML

Within the HomeController, I have the following method, [HttpGet] public ActionResult GetStudents() { Student std1 = new Student(); List<Student> stdlst = new List<Student>(); std1.Id = 1; ...

Activate Jquery as the user navigates through it with scrolling

Is there a way to activate a JQuery event when the user first scrolls over a particular div? I attempted to utilize waypoint for this purpose, but unfortunately, it did not work as expected. Below is the code I used with no errors: var waypoints = $(&apo ...

Troubleshooting intersecting objects in THREE.js

Having trouble detecting intersections of extruded objects in THREE.js. The objects are created from a 2D geometry as shown below: var geoShape = new THREE.Shape(vertexes); var geometry = new THREE.ExtrudeGeometry(geoShape, { bevelEnabled: false, amount: ...

Generate and delete dynamic iFrames through variable manipulation

I'm currently developing a landing page specifically for our pilots to conveniently access weather information before taking off. However, due to the limitations posed by our computer security measures, I can only utilize iframes to obtain the necessa ...

Form featuring two buttons with distinct values for submitting

<form action="here.php" method="POST"> <input type="text" name="text"> <div id="one"> <input type="hidden" name="aaa" value="one"> <input type="submit" value="Send"> </div> <div id="two"> <input type= ...

Retrieve the prior position using the AngularJS ui-router

Utilizing fromState and fromParams within the $stateChangeSuccess event allows us to access all details regarding the previous location. This concept is elaborated in the following discussion: Angular - ui-router get previous state $rootScope.$on('$s ...

In order to activate the input switch in Next.Js, it is necessary to initiate a

Currently, I am working on implementing an on-off switch in Next.Js. To seek assistance, I referred to this helpful video tutorial: https://www.youtube.com/watch?v=1W3mAtAT7os&t=740s However, a recurring issue I face is that whenever the page reloads, ...

Maintain the newly selected background color for the current day in fullcalendar when navigating to the next or previous month

Currently, I am working on a project in React using npm fullcalendar. One of the requirements is to change the color of the current day. After some trial and error, I was able to achieve this by adding the following code: $('.fc-today').attr(&ap ...

Looking to set a cursor style on a table row with JavaScript?

let table = document.getElementById(TABLE_NAME); let nextRow = table.tBodies[0].rows.length; row.setAttribute('style', "cursor: pointer;"); I am trying to implement a double click event on a table row, which is working as expected in most ...

What is the best way to incorporate the skrollr-body tag without altering the overall height of the

Skrollr has been a game-changer, so thank you to the geniuses behind it. I made sure to properly place the skrollr-body tag around all elements except for the fixed background in order to make it work on mobile. However, I'm noticing that it is cutti ...

Converting JavaScript code for Angular: A step-by-step guide

I have been working on integrating a feature similar to the one demonstrated in this Angular project: https://codepen.io/vincentorback/pen/NGXjda While the code compiles without any issues in VS code, I encountered two errors when attempting to preview it ...

The translation of popups using ngx-translate in Javascript is not functioning properly

When I click on my request, the content "Are you sure?" is not changing to the required language. This issue is located in list.component.html <button type="button" (click)="myrequest(item.Id)">Request View</button> The fu ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Place content following a three.js display created within a <div id="mainWindow">

Recently, I created a small Three.js animation and embedded it in my HTML page like this: <div id="mainWindow" class="popup_block"> <!-- JavaScript for simulation --> <script src="../temp/webgl-debug.js"></script> <scri ...

Exploring the hidden contents within the zip file

I have been exploring methods for reading 'zip' files. Two libraries that I have used are zip.js and JSzip. I have successfully viewed the contents of the zip file. However, here lies the challenge: My goal is to identify specific file types ...