Guidelines on updating syntax-defined variables in a controller?

Here is the code snippet I am currently working with:

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

var appCtrl = app.controller('AppCtrl', AppCtrl);

function AppCtrl(){
  var appCtrl = this;
  appCtrl.variable = "search";
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app = "app">
  <div ng-controller = "AppCtrl as ctrl1">
     {{ctrl1.variable}}
  </div>
  <div ng-controller = "AppCtrl as ctrl2">
    <input type="search" ng-model = "ctrl2.variable"/>
     {{ctrl2.variable}}
  </div>
</div>

After updating ctrl2.variable, the value of ctrl1.variable remains unchanged.

Is there a way to update it without resorting to using $scope?

Answer №1

If you're looking for a straightforward solution that doesn't involve using $scope.$watch, one approach is to utilize a shared state concept, as demonstrated below.

Essentially, both controllers have access to the same object reference, enabling observation of any changes made to the value.

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

app.factory('SharedState', SharedState);

function SharedState(){
  var shared = this;
  state = {variable: "search"};
  
  shared.getState = function() {
    return state;  
  }
  
  return shared;
}

app.controller('AppCtrl', AppCtrl);

function AppCtrl(SharedState){
  var appCtrl = this;
  appCtrl.sharedState = SharedState.getState();

}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app = "app">
  <div ng-controller = "AppCtrl as ctrl1">
     {{ctrl1.sharedState.variable}}
  </div>
  <div ng-controller = "AppCtrl as ctrl2">
    <input type="search" ng-model = "ctrl2.sharedState.variable"/>
     {{ctrl2.sharedState.variable}}
  </div>
</div>

Answer №2

Adricadar's response is completely adequate.

However, I'd like to share the code snippet that I wrote:

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

var appCtrl = app.controller('AppCtrl', AppCtrl);

appCtrl.$inject = ['ShareDataService'];

function AppCtrl(ShareDataService){
  var appCtrl = this;
  appCtrl.variable = "search";
 
   appCtrl.setSearchQuery = function () {    
       ShareDataService.setSearchQuery(appCtrl.variable);
    }
     
appCtrl.getSearchQuery = function () {    
        return ShareDataService.getSearchQuery();
    }
 
}

var sharedDataService = app.service('ShareDataService',ShareData);

function ShareData(){
  var shareDataService = this;
    
  shareDataService.searchQuery = "";

  shareDataService.getSearchQuery = function(){
return shareDataService.searchQuery;
  }

  shareDataService.setSearchQuery = function(searchQuery){
shareDataService.searchQuery = searchQuery;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app = "app">
  <div ng-controller = "AppCtrl as ctrl1">
     {{ctrl1.getSearchQuery()}}
  </div>
  <div ng-controller = "AppCtrl as ctrl2">
    <input type="search" ng-model = "ctrl2.variable" ng-change="ctrl2.setSearchQuery()"/>
     {{ctrl2.variable}}
  </div>
</div>

The principle behind it is as follows:

  1. Service acts as a Singleton Object, with only one instance created.
  2. Implemented setter and getter methods for functionality.

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

Is there a way to update and reload the latest data in ApexCharts?

Can anyone assist me in resolving my issue? I have an ApexCharts that displays data, and I need it to refresh whenever the user desires. The data should also be updated with the latest information. However, I am unsure how to reload the data in ApexCharts. ...

I am confident in my code, but why is eslint throwing an error? How can this be happening?

I have been diving into Vue render functions, and here is my index.js: <script> export default { name:'MyHead', props:{ level:Number }, render(h){ return h('div', [h('h'+this.level,'this is head&ap ...

The Angular2 cli throws an error stating: "Cannot add a new entry to an existing one."

I have been utilizing the Angular2 Cli as my runtime environment for my Angular 2 application and I must say, I am thoroughly impressed by its architecture, top-notch development tools, and overall well-thought-out design. However, every so often, specifi ...

Exploring Objects without the need for loops

Currently, I am focusing on optimizing the performance of the following objects: var scheduleFee = { poor = {level1:25,level2:25,level3:25} , good = {level1:15,level2:20,level3:25} , vgood = {level1:10,le ...

Tips for updating table row TD value using a query

I need to update the data-title="Status" value in a table. For example, if the data-status text is "DataSubmission", it should be changed to 'Inprogress' Here's the code snippet: $("#cpC_gvSearchResult tr td:contains('D ...

The current version of HTML5 Context Menus is now available

I'm in need of implementing the HTML5 Context Menu feature. Currently, only Firefox supports it. My main objective is to add some menu options without replacing the existing context menu. How can I achieve the same functionality now? I am aware of va ...

Displaying a checklist that shows all items that have been selected, rather than only showing the first selected item

I'm facing an issue with my data table that has checkboxes corresponding to each row. My goal is to append the contents of the selected rows into a "Favorites List" when the checkbox is clicked. However, I am currently only able to display the content ...

Clarification: Javascript to Toggle Visibility of Divs

There was a similar question that partially solved my issue, but I'm wondering if using class or id NAMES instead of ul li - such as .menu, #menu, etc. would work in this scenario. CSS: div { display:none; background:red; width:200px; height:200px; } ...

What is the best way to display images one by one from a map using a random fade effect?

I am in the process of creating a logo wall for a website. I successfully managed to display them randomly using a map, but now I want to make them appear one by one in a random order (for example: image 1, image 6, image 3, ...) and keep them visible once ...

Sometimes the downloaded xlsx file may become corrupted

Currently, I am working on developing a project using Angular4 with Typescript. One of the tasks involved creating a blob utilizing the XLSX-populate library. Below is an example showing the code snippet for generating a valid xlsx object: var url = wind ...

Having an issue where I receive the error message "this.cancelOrderFunction is not a function" when trying to execute a method within a child component in Vue.js

I'm facing an issue while trying to execute a method that changes the text content of the currentStatus variable when the Confirm Cancel button is clicked. The button is located in the child component within a dialog box, while the method is supposed ...

What sets Vue.js apart, class and staticClass - is there a distinction?

Can someone explain the distinction between class and staticClass in Vue.js render functions? While using Template Compilation, I noticed that the output varies based on what is provided to the HTML class attribute. For instance, when passing a single str ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

Incorporating a variable into a regular JavaScript pattern

In my JavaScript code, I have a variable assigned as var num = "x". How can I incorporate this variable into a regular pattern? var pattern = /"i want to include the variable num here"/i If I were working with a string, it would look something like this: ...

Expandable Grid Interface: Featuring a Button for Interactive Actions

Is it possible to include a button within an expandable sub-grid in Angular UI-GRID-info and have it call a function such as getExternalScopes().Validate, SaveRow, or DelteRow? {name: 'saveRow', cellTemplate: '<button id="saveBtn" type=" ...

Using an Angular variable in a JavaScript function may seem challenging at first, but with

Currently, I have an Angular component that utilizes a JavaScript library (FullCalendar V4). The library triggers a function when certain events occur (such as mouseover or click) and provides an argument that allows me to access the calendar values (start ...

What is the best way to test an Angular application using John Papa's style, as well as Karma and Jasmine, all while

Following the guidance provided by Josh in a post reply on unit testing John Papa's vm.model with jasmine, I am still unable to display my controller values in the testing area. It seems like the issue lies with the data service, which is essential fo ...

Sending a variable to the resize() function in jQuery

Currently, I am working with two specific divs in my project: "#sidebar-wrapper" and ".j1". The height of ".j1" is dynamic as it changes based on its content. My objective is to set this height value to the "#sidebar-wrapper" element. I have attempted to ...

What is the best way to configure angular $filter to perform case-sensitive string comparisons when filtering data?

I've been working on creating a case-sensitive filter in an Angular controller to filter an array. Here is the data: var stoneArr = [ { "stone_name": "Diamond", "id": 16 }, { "stone_name": "Ruby", "id": 1 ...

How can I update and edit the State in React when using a bootstrap modal?

I am currently working on a project listing table and facing an issue. How can I prefill input fields in a Modal with the clicked data, edit them, and update the state with the new information provided? Below is a breakdown of my code in different files: ...