Is it possible to incorporate an expression within NG-MODEL?

Is there a way to bind an expression inside the NG-MODEL directive without causing an error? Can this be achieved using a compile function? Below is my HTML markup:

<!DOCTYPE html>

<html>
<head>
    <title></title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body ng-controller="AppCtrl">
    <div></div>
    <range min="0" max="100" model="width"></range>
</body>
</html>
<script src="Scripts/angular.min.js"></script>


<script>

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

app.run(function($rootScope){

    console.log($rootScope);    

});

angular.element(document).ready(function(){

    angular.bootstrap(document.querySelector("html"), ["pager"]);

})

app.directive("range", function ($compile) {

    return {

        restrict: "E",
        replace: true,
        scope:{

            min:"@",
            max:"@",
            model:"@"

        },
        template: "<input type='range' ng-model='{{model}}' value='0' min='{{min}}' max='{{max}}'/>",

    }

})
</script>

When using ng-model='{{model}}', it generates an error. Is there a method to directly access the model attribute from the directive and create the variable for ng-model without errors? Would linking it that way work, or do I need to utilize $compile? The goal is for directives to generate variables in the child scope and then bind them to the ng-model they are creating. In this case, I aim to use the attribute "model" from the directive to establish the variable for the ng-model. For instance, in this scenario, "width" should replace the {{model}} expression.

Answer №1

Is this the solution you've been searching for?

If you switch out the @ with the =, you'll be able to view it on your controller $scope (without utilizing an expression). Check out the code snippet and demo below.

Update

app.directive("range", function ($compile) {
    return {
        restrict: "E",
        replace: true,
        scope: {
            min: "@",
            max: "@",
            model: '='
        },
        compile: function () {
            return {
                pre: function (scope, elem, attrs) {
                    // The isolated scope of the directive
                    console.log(scope);
                    // Scope of the controller
                    console.log(scope.$parent);
                }
            }
        },
        template: "<input type='range' ng-model='model' value='0' min='{{min}}' max='{{max}}'/>"
    }
});

Check out the Fiddle

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

"Can anyone help me understand the error that is popping up in my AngularJS function when I pass in

Below is the code snippet : ng-click="create({{item.variants[0].id}},{{item.variants[0].title}})" When running this code, I encountered the following errors : Error: [$parse:syntax] Syntax Error: Token 'Title' is unexpected, expecting [)] at c ...

Guide to showing an uploaded image in a child component using Vue.js

Using the v-file-input component from Vuetify, I am able to upload images with the following code: <v-file-input label="Image" filled accept="image/png, image/jpeg, image/bmp" prepend-icon="mdi-camera" v-mod ...

"pre and post" historical context

Is there a way to create a stunning "Before and After" effect using full-sized background images? It would be amazing if I could achieve this! I've been experimenting with different examples but can't seem to get the second 'reveal' di ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

Converting PDF files to JSON in ASP.NET and transferring them to AngularJS using Base64 does not result in identical files

After encoding a PDF file as Base64 and assigning it to a property of my model object in ASP.NET WEB API, the JSON response is received by my AngularJS client application. However, upon saving the file, I noticed that the file size increases by one and 1/3 ...

Executing Promises in an Array through JavaScript

LIVE DEMO Here is a function provided: function isGood(number) { var defer = $q.defer(); $timeout(function() { if (<some condition on number>) { defer.resolve(); } else { defer.reject(); } }, 100); return defer.pro ...

Packages and Digital Routes

Currently in the process of creating a new website utilizing angular, MVC, and Web API. The plan is to keep the static content (js, css, images, etc) in Site A, the MVC site in Site B, and the api in Site C. These will be separate sites, not virtual direct ...

JQuery UI autocomplete vanishes instantly without any warning

I am encountering an issue with JQuery UI's autocomplete feature where the dropdown results do not stay visible. While debugging, I noticed that the list briefly appears before disappearing. Below is my code snippet: HTML: <input type="text" plac ...

Is there a way to incorporate promises into an endless loop while adding a delay in each iteration?

require("./getSongFromSpotify")().then(a => { require("./instify")(a.artist,a.name).then(r => { if (r.status === "ok"){ console.log("saved") }else{ console.log(" ...

What is the best way to rearrange DOM elements using the output of a shuffle function?

Looking for a solution to shuffle and move around cards in an HTML memory game? Let's analyze the current setup: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

Trouble with Global Variable Allocation in jQuery Ajax

I've got a script that includes a jQuery Ajax call: <script type="text/javascript"> $(document).ready(function() { var timer; $.ajax({ type: 'POST', url: 'closettime.php', success: function( res ) ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

The onInvoke hook in Zone.js is receiving an inaccurate currentZone value

Greetings. In the comments for the ZoneSpec interface (found in zone.ts file), it states that the onInvoke hook must receive currentZone as the second parameter. If creating an interceptor zone, the reference to that zone should be passed as the second pa ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

Strategies for consistently receiving updates of Iframe content body within a react useEffect hook

When loading html into an iframe using srcDoc with the sandbox="allow-same-origin", I face a challenge. Despite the content displaying properly, the property frameRef.contentDocument.body.innerHTML remains empty. This issue persists even after s ...

Assigning alphanumeric characters to the axis for identification purposes

review the code in index.html <!DOCTYPE html> <html> <head> <title>D3 test</title> <style> .grid .tick { stroke: lightgrey; opacity: 0.7; } .grid path { stroke-width: 0; } .ch ...

Is there a way to pass a token variable from the main page to an iframe without relying on a post message?

I am seeking assistance on how to transfer a variable from a parent window to an iframe. My situation is as follows: I am working with 2 Angular5 applications named A and B . Application B is loaded within Application A using an iframe. The aut ...

Creating Functional Tabs Using CSS and JavaScript

I've been experimenting with this code snippet, trying to get it to work better. It's still a work in progress as I'm new to this and have only customized it for my phone so far. The issue can be seen by clicking on the Projects and Today ta ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...