Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach:

angular.module('myapp',[]),directive('mydirective', function() {
    var directive = {};
    directive.restrict = 'E';
    directive.replace = true;
    directive.templateUrl = 'mydirective.html';
    directive.scope = {
      myModel : '=',
    };
    directive.controller = function($scope){
        // Controller logic here
    }

    directive.link = function($scope, $element, attrs) {
        // Link function logic here
    };
  return directive;

Template example:

<div ng-model="name">
</div>
<div ng-model="age">
</div>

Utilizing the directive:

In the directive controller, I aim to manipulate 'name' and 'age' without affecting the parent model. Once the necessary operations are completed, I will then update the parent model accordingly.

Answer №1

By using scope: {myModel:'='}, you are creating a new isolated scope where myModel is connected to the parent's myModel. This means that any changes made to scope.myModel will also affect scope.$parent.myModel.

However, if you want to have your own independent model in the new scope, you should do the following:

link: function(scope) {
   scope.model = angular.copy(scope.myModel); // creates a new object model with all values from the parent

   scope.saveModel = function() {
       scope.myModel.age = scope.model.age;
       scope.myModel.name = scope.model.name; // updates values in the parent
   }

Then, in your directive template, use model as the ng-model:

<input ng-model="model.name" />
<input ng-model="model.age" />
<button ng-click="saveModel()">apply</button>

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 can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

I'm curious, does a specific event get triggered when an item is added to a UL element?

Is there an event that gets triggered when a new item is added to a UL list? I am on the lookout for something like this. Thank you! ...

Button inside table cell not showing Bootstrap tooltip

I've implemented a feature where each row in a table has a button that triggers a pop-up modal when clicked. I want these buttons to display tooltips when hovered over and when focused. Below is an example of the HTML structure: <link hr ...

two adjacent elements filling the entire height of the window at 100% dimensions

Is there a way to place two elements side by side, with one of them (the textarea) always being 100% height of the window? I've looked at similar questions here but can't figure out how to make it work. Can you help me with this? html: <div ...

Integrating a footer into the enhanced search tab slider

I'm struggling to create a sticky footer like the one on w3schools. Even though I used the same code in my material UI demo, it's not functioning properly. I tried debugging by changing the position from fixed to absolute, but it still isn&apos ...

Converting from Async.js parallel to Bluebird: A Step-by-Step Guide

Utilizing async.js allows me to define promises with handlers, providing polymorphism and separating results. Can this be achieved in bluebird as well? async.parallel({ cityPromises: (cb)=>{ City.find({ ...

Exploring the world of Polymer's Paper Elements and Angular Material

I need assistance in deciphering these quotes from the Angular Material GitHub and official website: It should be noted that this project is still in its early pre-release stage. Angular Material serves as a reference implementation of Material Design whi ...

Steps for Implementing an Event Listener in JavaScript

While working on a page in Chrome, I encountered an issue where I wanted a modal to show up when a user clicked on an image. However, the functionality was not working as expected on my localhost. Upon further inspection, I believe there might be a problem ...

Encountering an unrecognized error on Windows when attempting to execute a child process with regex return

Below is the code I am utilizing to retrieve Make file targets: const command = `make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\\/t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'`; cp.exec(command, options, (error, stdout, s ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

Is there a way to exchange the chosen options between two bootstrap-vue multiple select boxes?

Is there a way to switch the selected options between two bootstrap-vue multiple select boxes? I am trying to create a UI similar to the image shown below but I am struggling with writing the method. This is how I have written the template: https://i.sst ...

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...

JavaScript - Global Variable

Is it possible to declare and assign a value to a global variable in one JavaScript file and then reference it in another JavaScript file multiple times? Can Angular.js be utilized in a Velocity macro file, aside from HTML files? ...

Tips for transforming JSO into JSON data format

Here is an example: var info = [{"name":"john","age":"30"},{"name":"smith","age":"28"}] I am looking to convert the above json object to a format like this result: [{name:"john",age:30},{name:"smith",age:28}] Any suggestions on how to achieve this? ...

Guide on creating a function that accepts an Array of strings as a parameter and displays the initial letter of each element individually on separate lines

I am currently tackling my initial JavaScript assignment which involves the task of creating a function that accepts an array of strings as its parameter and outputs the first letter of each element individually on separate lines. The unique requirement ...

Having issues with image hover and click functionality

My website has an image with the cursor set to pointer and a function that should show a hidden element when clicked. However, it's not working at all. When I hover over it or click on it, nothing happens. Here is a screenshot of the issue along with ...

Using jQuery to Navigate through Different Routes in React Router

Hey there, I've managed to get my React-Router set up quite well but now I'm facing a new challenge. I need to implement some JavaScript functionality. For example: When the user enters their login details and clicks 'login', I want my ...

What is causing errors in my Yeoman build when I use Ruby and Gems paths?

Currently, I am utilizing Yeoman to construct an Angular.js application. I have chosen to enable support for Sass and Compass in it. However, when attempting to build with Grunt, the process fails due to inability to locate Ruby for compiling the scss file ...

Navigate to the end of the progress bar once finished

I have a solution that works, but it's not very aesthetically pleasing. Here is the idea: Display a progress bar before making an ajax call Move the progress bar to the end once the call is complete (or fails) Keep the progress bar at 90% if the aj ...