Is there a way to attach a model to an Angular directive?

Currently, I am implementing angular's typeahead functionality using the following resource:

I have created a directive with the following template:

<div>
    <input type="text"
           ng-model="user.selected"
           placeholder="Type to select . . ."
           typeahead="item as item.name for item in getData($viewValue)"
           typeahead-loading="loadingData"
           class="form-control">
    <i ng-show="loadingData" class="glyphicon glyphicon-refresh"></i>
</div>

The directive code is as follows:

return {
    restrict: 'AE',
    replace: true,
    scope: true,
    templateUrl: 'type.html',
    link: function (scope, elem, attrs) {
        var url = window.location.origin + attrs.url;

        scope.getData = function (val) {
            return $http.get(url, {
                params: {
                    q: val
                }
            }).then(function (response) {
                return response.data.map(function (item) {
                    return item;
                });

            });
        };

    }
};

This directive can be used as shown below:

<my-directivw url="api/user">   </my-directive>

Now, instead of setting ng-model="user.selected" directly in the template, I want to use another variable. How can this be achieved?

You can achieve it by modifying the directive call as follows:

<my-directive url="api/user" somevar="user.selected">   </my-directive>

Please advise on how to proceed.

Answer №1

Perhaps this information will be beneficial to you.

This is an example of the HTML code structure:

<div ng-app="app" ng-controller="Ctrl as ctrl">
    <form name="theform">
        <range ng-model="ctrl.theRange" name="myRange" required="true"></range>
    </form>
    <button ng-click="ctrl.theRange = '10/100'">SET</button>
</div>

Here is how the JavaScript code looks:

var app = angular.module("app",[]);

app.controller("Ctrl", function($scope) {
    this.theRange = "1/7";
});

app.directive("range", function() {
    var ID=0;

    function constructRangeString(from, to) {
        var result;
        if( !from && !to ) {
            result = null;
        }
        else if( from ) {
            result = from + "/" + (to || "");
        }
        else if( to ) {
            result = "/" + to;
        }
        return result;
    }

    return {
        require: "ngModel",
        restrict: "E",
        replace: true,
        scope: {
            name: "@"
        },
        template:
            '<div ng-form="{{ subFormName }}">' +
                '<input type="text" ng-model="from" class="range-from" />' +
                '<input type="text" ng-model="to" class="range-to" />' +
            '</div>',
        link: function(scope,elem,attrs,ngModel) {
            var re = /([0-9]+)\/([0-9]+)/;

            if( scope.name ) {
                scope.subFormName = scope.name;
            }
            else {
                scope.subFormName = "_range" + ID;
                ID++;
            }

            ngModel.$render = function() {
                var result, from, to;
                result = re.exec(ngModel.$viewValue);
                if( result ) {
                    from = parseInt(result[1]);
                    to = parseInt(result[2]);
                }
                scope.from = from;
                scope.to = to;
            };

            scope.$watch("from", function(newval) {
                var result = constructRangeString(newval, scope.to);
                ngModel.$setViewValue(result);
            });
            scope.$watch("to", function(newval) {
                var result = constructRangeString(scope.from, newval);
                ngModel.$setViewValue(result);
            });
        }
    };
});

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

Determining the background image size of a div when the window is resized

I'm facing a problem that I can't seem to solve. I have a div with a background image. <div class="a"></div> I want to make a specific point of this background image clickable. I know I can achieve this by adding a div with a z-inde ...

Maintain the fancybox open even in case of ajax errors

I'm having an issue with my code where the fancybox closes automatically after displaying the error message briefly. I want it to remain open so that users have more time to fix their errors. What could be causing this problem? $(document).ready(func ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Arranging an array of arrays based on the mm/dd/yyyy date field

Currently, I am facing an issue while attempting to sort data obtained from an API by date in the client-side view. Here is an example of the data being received: address: "1212 Test Ave" address2: "" checkNumber : "" city: "La Grange" country: "" email: ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

What is the best way to send an object array from an express function to be displayed on the frontend?

//search.js file import axios from "axios"; export function storeInput(input, callback) { //input = document.getElementById("a").value; let result = []; console.log(input); if (!callback) return; axios.post("ht ...

Please upload the image by clicking the "Upload Files!" button instead of relying on the input change

I am looking to enhance my image uploading process by allowing users to upload multiple images after clicking the Upload Files! button, rather than relying on the input change event. Below is the jQuery code I am using (which I found here): index.html &l ...

Keystroke to activate Ant Design Select and start searching

I'm currently using the 'react-hotkeys-hook' library and have successfully implemented a hotkey that logs in the console when triggered (via onFocus()). My goal now is to use a hotkey that will open a Select component and add the cursor to i ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Reset the AJAX object using jQuery

Currently, my code looks like this: object1 = $.ajax({ .. .. }); If an error occurs, I would like to have the ability to restart the ajax request. For instance, if the user's connection is lost, I want to be able to easily call the same ajax again w ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

MongoDB Driver Alert: MongoError - Cursor Not Found. Cursor ID 7820213409290816 was not located in the specified namespace db_name.collection_name

Having successfully created a Nodejs API server that connects to AWS MongoDB (version: 3.6), everything seems to function flawlessly when calling one specific API endpoint (api/lowest). However, upon making multiple simultaneous calls to this API (15 in to ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

When validating an array in JavaScript, it is important to note that not all elements may be displayed. Only the last variable of each element will

I am encountering an issue with validating an array of objects, specifically a table with rows where each row represents an object. The problem is that no error message appears if there is an error in the middle row of the table. However, if there's a ...

Connect Promise.all() with an array of identification numbers

I'm fairly new to working with Promises and I have a question regarding linking the results of `Promises.all()` to unique IDs for each promise once they resolve. Currently, I am making requests to a remote server and retrieving data for each request. ...

When should one close a custom-built jQuery dropdown menu?

I created a simple dropdown using a <div> (parent), <span> (current selection), and <ul> (options) which is functioning properly. Now, I'm looking to enhance it by implementing a feature that allows the dropdown to close when the use ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...