Breaking up the HTML elements assigned to a single controller can render the controller inoperable

When I create two divs controlled by the same controller in Angular, I notice that the controller stops updating my view.

To illustrate this issue, I have prepared a simple example. You can view the sample here on JSFiddle, or you can also refer to the code below.

HTML

<div ng-app='App'>
    <div ng-controller="MyCtrl">
        <form>
            <input type="text" ng-model="search.query"></input>
            <button ng-click="search.submit()">Submit</button>
        </form>
    </div>
    <div ng-controller="SomeOtherCtrl">
        {{sampleText}}
    </div>
    <div ng-controller="MyCtrl">
        <button ng-click="search.reset()">Reset Form</button>
    </div>
</div>

JS

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

function MyCtrl($scope)
{
    $scope.search = {
        query : 'foobar',
        submit : function() {
            this.query = 'Submitted';
            console.log(this.query);
        },
        reset : function() {
            console.log('resetting');
            this.query = '';
        }
    };
}

function SomeOtherCtrl($scope) {
    $scope.sampleText = 'other controller text';
}        

Upon clicking the submit button, everything works as expected. However, when clicking on the Reset button, although I see resetting being logged in the console, the view (the form input) does not update.

I am facing this issue in a current project where certain HTML elements belong to another controller. How can I address this challenge?

Answer №1

Angular defines a controller as a Class / Constructor instead of an Object. When referenced in the HTML, Angular creates a new controller object using the specified class during compilation. This allows multiple scopes to be referred to with the same controller class.

In situations like this, where two controller instances share a common object such as search, it is recommended to use services in Angular. By using two ng-controller="MyCtrl", Angular creates two instances of MyCtrl with access to different scopes and search objects. Clicking on reset will only affect the corresponding search object's scope, leaving the other unchanged.

It's important to note that Angular services are singletons, so referencing them in multiple places accesses the same object. Resetting in a different controller instance will still reset the original object.

To see a working example, check out this plunk:

http://plnkr.co/edit/zynAdS9hg8DUZDnlnYFm?p=preview

Answer №2

My understanding of angularjs is limited, but it seems that placing a second input

<input type="text" ng-model="search.query"></input>
next to the reset button will result in this input being updated. Should both inputs be contained within the same div controller? Do you think this approach could potentially resolve your issue?

Answer №3

Upon reviewing your example, it appears that you have overlooked adding a form tag for the reset button. In an Angular context, consider wrapping your code in an outer div with the controller attribute set to "MyCtrl". Inside this div, create a form with two buttons - submit() and reset(). Furthermore, within the outer div, include another nested controller called "SomeOtherCtrl". By following this structure, your code should function smoothly.

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

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

When passing down data to a child component, the value is not accessible

I'm facing an issue where I am trying to pass down the isOpen prop to the Snackbar component. However, when I try to console.log this.props in either the componentDidMount or componentDidUpdate methods, all I see is this.props.message. I would really ...

Setting Default Value for Autocomplete in React

I'm facing an issue with the default value in my autocomplete feature within my React app. Even though I set a default value, when I try to submit the form, it still shows as invalid because it appears to have no value until I manually click on the au ...

Buttons in Highcharts

Is there a way to incorporate a button within a highcharts graph? I am working with a bar chart and would like to include a button on the left side of the label, similar to the example shown in this bar chart demo. I want the button to appear before the ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

Is JQueries Live functionality compatible with IE8?

Incorporating the JQuery fancy box, I have implemented a pop-up form with select fields that dynamically update a span element upon selection change. Although it works well thanks to fellow Stack Overflow users' help, it unfortunately does not functio ...

Troubleshooting NodeJS and Express: Issue accessing a function located outside a folder

I'm having trouble accessing the function I exported in app.js Here is the code snippet from app.js: function getConnection() { return mysql.createPool({ host: 'localhost', user: 'root', password: &apo ...

Developing a fresh instance in JavaScript

Currently, I am working with a JSON object that I'm required to use in my project. const template = require('../../../../assets/jsons/article-tpl.json'); Next, I need to iterate through an array and utilize this object to generate a new te ...

Issues with ng-repeat not functioning properly within a Popover

I have a list that I am looping through using ng-repeat: <div class="row msf-row" ng-repeat="record in recordlist people-popover> <div class="col-md-1 msf-centered" ng-show="editItem == false" ng-hide="editItem"> <button class="btn ...

I'm having trouble getting the infoWindow to function properly

As someone who is new to JavaScript, I recently came across a question on Google Maps JS API v3 - Simple Multiple Marker Example and attempted to implement the solution provided by Daniel Vassallo. var Australia = new google.maps.LatLng(-27.16881, 132.7 ...

Load Vue 3 components dynamically using a string-based approach

Exploring ways to dynamically load components based on a string input. Here is an attempt at achieving this: <component v-for="component in components" :is="eval(component)" /> However, this approach does not yield the desired r ...

Angular: module instantiation unsuccessful

Just getting started with Angular and running into an issue where the module seems to be unavailable. https://docs.angularjs.org/error/$injector/nomod?p0=plopApp My code is very basic at the moment, just setting things up: @section scripts{ <script s ...

What is the best way to link JavaScript files from a Grails plugin in a separate Grails application?

I have developed a unique plugin that offers multiple Grails controllers and domain objects. Additionally, I have created several AngularJS UI components that I wish to utilize in various other projects. These specific files are located within the web-app ...

Is there a way I can detect a browser timeout and display a custom error message?

My webpage in classic asp contains a link to a local IP address, shown below: <a href="http://192.168.1.89">Link</a> When the local IP address is not available, the web browser eventually times out and shows its own error message. I ...

When attempting to retrieve $rootScope data within a factory, the result is undefined

I am perplexed by a coding issue. Initially, I encountered this problem while working with Ionic 1+ (although I suspect it may be related to AngularJS). I decided to create a factory and inject $rootScope into it. In my app.js file, I defined a variable ...

Encountering an issue with the npm start command in my React application

After using npx create-react-app basic to create a React app, I navigated to the basic folder and attempted to start it with npm start. However, I encountered the following error: npm start <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

What is the best way to automatically have the first bar in a column highchart be selected when the page loads?

My highchart consists of a simple column. When I click on any bar in the chart, it gets selected. However, I also want the 1st bar to be selected by default. var chart = $('#container').highcharts(); Upon page load, I have obtained this object. ...

There was no popcorn mix-up in your document

Encountering an issue while using grunt for staging (grunt serve): Running "bower-install:app" (bower-install) task popcornjs was not injected into your file. Please check the "app\bower_components\popcornjs" directory for the required file, an ...

Issue with automatic form submission

What is the best way to automatically submit my form once the timer runs out and also when the refresh button is clicked? I have encountered an issue where every time I try to refresh the page, it prompts for user confirmation. If I click cancel, it stay ...