Guidelines for passing input values from a custom directive using $resource in Angular

I have been researching how to use ngModel within a custom directive, and while I grasp the concept, I am struggling with implementing it when using $resource.

Currently, I am successfully injecting the "file" scope into my directive and making the API call. However, the value being returned to my server is showing up as null. It seems that my Angular directive implementation may be where the issue lies.

directive.js

angular.module('pro').directive('buyLinkBox', function() {
     return {
        restrict: "AE",
        replace: true,
        template: '<md-input-container md-no-float md-block><label style="font-size:2.2vh">Buy Link for {{file.filename}}</label><input type="text" ng-blur="sendLink()" ng-model="file.buyLink" name="buyLink" id="buyLink"/></md-input-container>',
        scope: {
            file: '=',
        },
        controller: function($scope, $route ,BuyLinkService){

            $scope.sending = BuyLinkService.get({
                FileId: $scope.file._id
            });

            $scope.sendLink = function() {
                $scope.sending.$sendLink(function() {
                    $route.reload();
                }, function(errorResponse) {
                    alert('nope');
                });
            };



        }
     }
});

html

 <buy-link-box file="file"></buy-link-box>

Answer №1

Through deduction and troubleshooting, I managed to find a resolution.

The key steps I took included adding the ngModel to the directive scope and ensuring it was present in my HTML. However, the main issue stemmed from my resource being called before receiving the necessary data. The solution turned out to be straightforward - I implemented a callback function and assigned my desired field to the input variable PRIOR to initiating the PUT API call.

I hope this explanation proves beneficial to others facing a similar challenge.

directive.js

angular.module('pro').directive('buyLinkBox',['BuyLinkService', '$route', 
    function(BuyLinkService, $route) {
     return {
        restrict: "E",
        replace: true,
        template: '<md-input-container md-no-float md-block><label style="font-size:2.2vh">Buy Link for {{file.filename}}</label><input type="text" ng-blur="sendLink()" ng-model="ngModel" name="buyLink" id="buyLink"/></md-input-container>',
        scope: {
            file: '=',
            ngModel: '='
        },
        link: function(scope, element, attrs){

            scope.sendLink = function() {
                BuyLinkService.get({MixedId: scope.file._id}, function(data){
                data.buyLink = scope.file.buyLink;
                data.$sendLink(function(file) {
                    alert(file.buyLink);
                    $route.reload();
                }, function(errorResponse) {
                    alert('nope');
                });
            })
          }
        }
     }

}]);

html

<buy-link-box ng-model="file.buyLink" file="file"></buy-link-box>

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

How to conditionally prevent event propagation to children in VueJs

This Vue component is called ColorButtonGroup, and it serves as a group of checkbox/toggle buttons. It has a maximum limit of 4 colors that can be selected. The component utilizes another component called ToggleButton, which is a simple toggle selection w ...

Troubleshooting Problems with Fancybox Scaling on Small Landscape-Oriented Mobile Devices

Issue Description: In my responsive web design, I am utilizing Fancybox v2.1.5. The problem arises when smaller mobile devices with a more rectangular shape than square are used. In portrait orientation, when invoking Fancybox, it expands to the width of ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

What is the best way to calculate the width for each of the three elements in a row so that they all have 300px

Creating my own framework using flexbox has been an interesting journey. One of the major challenges I faced with flexbox is when dealing with an odd number of elements in a row, such as 3, 5, or 7. To tackle this issue, I decided to use JavaScript/jQuery. ...

Learn how to seamlessly update broken images on a webpage with a placeholder error image using the MooTools 1.2 framework

Currently working on a project with PHP, MySQL and utilizing Mootools 1.2 as the JavaScript framework. I am trying to find a way for all broken images to automatically be replaced with a designated error image. Any suggestions on how I can achieve this? ...

Retrieving the Short Date Format from the user's device or browser within a React application

Currently, I am in the process of utilizing reactjs along with material UI datepicker. My objective is to transmit the short date format to the datepicker component, such as format="MM/dd/yyyy". In addition, I wish to employ the pre-existing date ...

Tips for Utilizing Environmental Variables within a Vue Application's index.html File

My website has an index file with all the necessary meta tags, stylesheets, and scripts: <!DOCTYPE html> <html lang="en"> <head> <!-- Required Meta --> <meta charset="UTF-8"> <meta http-equi ...

Leveraging periods within a MySQL database: Node.js for seamless updates

I am currently facing a challenge in updating a column name that contains a period in node using node-mysql. I appreciate the convenience of being able to update multiple columns by providing an object with keys, but the string escaping process with node-m ...

How to integrate a While loop within an RXJS subscription

I have a piece of Angular code where I am attempting to subscribe to my first API and include a while loop within this subscription. Additionally, I need to subscribe to another API inside the while loop. The reason for this is that I need to subscribe t ...

Unable to trigger ng-click event on an element that has been compiled in a controller

Is there a way to utilize $compile in order to enable ng-click functionality on a specific code block? Currently, my code is set up to display a suggestion box when certain event parameters are met. However, I am looking to give users the ability to hide t ...

Utilizing Node.js to Retrieve a POST Request JSON and Modify its Format

Received an incoming Post request in JSON format like this: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] Need to transform it into the f ...

iteration using underscores in JavaScript

I am currently working on creating an object using underscore and backbone. I have an array of objects, each containing a nested object with different sets of data. Within the array, data[0] holds the name of a location while data[2] contains the coordina ...

Issue in Jquery: Unable to load the corresponding pages when toggling the checkbox on and off

I am facing an issue with a checkbox and calling different php pages based on the status of the checkbox. Currently, the code works only for checked checkboxes. I'm not sure why it's not working for unchecked checkboxes as well. <script type ...

Preserve the status of expanded nodes within the jqGrid tree grid

How can I make sure the Expanded State of my JQTree Grid is persistent? I want it to retain its previous expanded state even after reloading the grid. Can anyone guide me on how to achieve this? Thank you in advance! ...

What is the best way to iterate through JSON objects stored in a single location?

Currently, I am dealing with a single JSON object structured as follows: Object --> text --> body --> div Array[20] --> 0 Object --> text --> body --> div Array[20] --> 1 Object --> text --> body --> div Array[20] --> . ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Attempting to send an AJAX request to a different server (not functioning with the provided example)

UPDATE - Issue Resolved. Many thanks to everyone who provided input. After conducting extensive research, I discovered that instead of CORS, I needed to focus on JSONP all along. I have read several tutorials and believe I now have a good grasp of the con ...

Are there any unique approaches to calculating PI through the use of lazy evaluation sequences?

Recently, I've been utilizing lazy.js in my JavaScript projects. One interesting question came to mind - is there a clever method to define PI using lazy evaluation, without actually calculating it? I understand that lazy evaluation is call-by-need, ...

Providing Node-server with Vue.js Server Side Rendering

I've been attempting to deploy the Hackernews 2.0 demo on my Digital Ocean droplet but have hit a roadblock. npm run start starts the server on port :8080. npm run build is used for production builds. The specific build tasks can be found below: ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...