Using Angular's ng-model Across Multiple Views

Is it possible to use ng-model to gradually build an object across multiple views?

For example, in view1 I have

<input ng-model='myObject.firstName'>

And in view2 I have

<input ng-model='myObject.lastName'>

And in view3 I have

<input ng-model='myObject.email'>

The concept is that you could click a submit button in the final view and send the object somewhere.

My initial approach is to create a service that initializes an empty object, then have functions within the service that allow controllers using the service to add their view input to the object and return it. However, I feel like this method is somewhat indirect!

If anyone has suggestions on a better approach, I would greatly appreciate it.

Answer №1

If you need to implement shared objects among multiple controllers in AngularJS, you can achieve this by using directives like ng-model. Here's an example where 3 controllers share the same object and update its properties.

angular.module('test', []).factory('tested', function() {
  return {
     value : '123'  
  };
}).controller('ctrl1', function($scope, tested) {
  $scope.tested = tested;  
}).controller('ctrl2', function($scope, tested) {
  $scope.tested = tested;  
}).controller('ctrl3', function($scope, tested) {
  $scope.tested = tested;  
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="test">
  <div ng-controller="ctrl1">
    <input type="text" ng-model="tested.value" />
    {{ tested.value }}
  </div>
  
  <div ng-controller="ctrl2">
    <input type="text" ng-model="tested.value" />
    {{ tested.value }}
  </div>
  
  <div ng-controller="ctrl3">
    <input type="text" ng-model="tested.value" />
    {{ tested.value }}
  </div>
</div>

Answer №2

When dealing with separate controllers for each view, the most effective way to share data is by utilizing a service of type "provider", "service", or "factory".

This approach allows you to manipulate your object from any controller using the specified methods.

To ensure that every view is aware of changes in the shared data, the service methods can trigger an event using:

$rootScope.$broadcast('somethingChanged', myObject);

Subsequently, each controller can listen for this event using:

$scope.$on('somethingChanged', function(data) { 
});

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

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

Using ng-class directive with condition in AngularJS

Here is a unique pop-up that allows users to encode item information. https://i.sstatic.net/sn9QZ.png I need to implement a feature where, if both the Foreign Currency and Conversion Rate fields have values, the Amount should be calculated by multiplying ...

Manipulating classes with JQuery through click events

$('.toggle-button').on('click', function() { $('body').addClass('changeCursor'); }); $('.toggle-button.toggle-active').on('click', function() { $('body').removeClass('c ...

Node JS server terminated due to invalid arguments: string and undefined

Currently, I am in the process of developing a logging application using node JS. Unfortunately, there seems to be an issue with the password authentication functionality within the app. Every time I enter a username and password, it triggers an error that ...

Comparison of Fabric JS Filters and CSS Filters

We are currently in the process of transitioning a project from HTML and CSS to Fabric JS. This project allows users to manipulate images by moving them around and applying filters. In our current HTML/CSS implementation, we handle image positioning with C ...

Loop through the JSONP object to display its properties

When I receive this object through jsonp, it has the following structure: "item1": { "child1": { "nr": 123, "money": "USD", "Date": "12.12.2016, 17:00", "asw1": 13, "SpecialField" ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

Transmitting an Ajax request via property path

I'm experiencing issues with sending data to the server. Here is my Ajax call: $.ajax({ url: config.api.url, type: config.api.method, contentType: config.api.contentType, dataType: config.api.dataType, data: config.api.dataType === ...

Setting the default date in angular-bootstrap-datetimepicker: a step-by-step guide

I am currently utilizing the angular-bootstrap-datetimepicker module for allowing users to choose a date and time. How can I set a default date and time when the view initially renders? Is there an attribute available that allows us to assign a boolean val ...

The node-static tool is limited in its ability to serve folders that are located outside

It's unclear whether this issue is a limitation of node-static or if there's an error in my code. I'm unable to serve files from directories above or below the current one. Here's the structure of my current directory: project publ ...

Revamp local route variables in Express.js without the need for a page refresh

Currently, I am working on a project using node.js along with the express.js framework and EJS for template handling. Below is my routing code: app.get('/',function(req,res) { res.render('index', { matches: [], status_messag ...

Establish a WebSocket connection via Meteor.js

How do we establish a Websockets connection in Meteor? Can we achieve this using the following code: ws = new WebSocket('ws://localhost/path'); ws.on('open', function() { ws.send('something'); }); ws.on('message&apo ...

Rotating an object around another object in a 3D matrix axis using Three.js

I currently have the ability to rotate one axis. Here is the code that's working now: https://codepen.io/itzkinnu/full/erwKzY Is there a way to rotate an object on a random axis instead of just one fixed axis? Maybe something similar to this exam ...

Is it possible to modify the URL parameter of a website?

The URLs on this website all include "#" and appear untrustworthy. While I'm not well-versed in JavaScript and Ajax, it's clear that the site was not designed with SEO in mind. The company that created this site was unable to change the parameter ...

Instructions for aligning an Object3D's face with another face (such as the floor) using object rotation

Situation Imagine a scenario where there is a floor and an object hovering directly above it. My Goal I am attempting to create a function where, upon clicking on a face of the object, the entire object will rotate so that the clicked face is facing the ...

ExpressJs responds with an empty JSON object

During the validation of a mongoose schema within 'pre' of parallel middleware schema.pre('save', true, function (next, done) { if(...) { next(new Error('Some error message')); } next(); }); After returning an err ...

Using Ajax requests in WordPress

I am working on creating a button that will send an email to the branch of the user who is logged in. To get started with the coding process, I need to ensure that the AJAX call is sent successfully and triggers the 'success' method of the AJAX o ...

Tutorial on creating a loop for a function based on a specific condition

I have created two different div classes named box and box2. The box2 class can be dragged and dropped into any of the three box classes. Each box contains randomly chosen values from an array, while box2 contains its corresponding image for display. When ...

What could be the reason for the active class not being triggered by Bootstrap?

After making an Ajax call to a PHP file from jQuery, I am trying to loop through the information and format it within table rows and cells. Specifically, I want to use the <tr class="active"> class and the <tr><td> structure provided by B ...

Having trouble with the autocomplete feature on your textbox in CodeIgniter?

controller: Welcome.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { function __construct() { parent :: __construct(); $this->load->helper ...