If I create two div's, both controlled by the same controller, Angular's controller seems to stop updating my view.
I've put together a bare-bones example to demonstrate this. It is easiest to view the sample here on JSFiddle, but I'm also posting 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';
}
The submit button works fine, but when I click on the Reset button, I see resetting get logged in the console, but my view (the form input) does not update.
Why is this so? In a current project I'm working on, I'm forced to do this because certain HTML that falls in between belongs to another controller. How can I work around this?
A controller definition in angular is actually a Class / Constructor and not an Object. Each place in the HTML that controller is referenced, during the compilation phase, angular creates a new controller object using the defined controller class. So, you could refer to more than one scope with the same controller class.
You might have already heard of services in Angular and this is exactly a place where you need to use them to solve it. search that you are using is a common object that is being shared by two controller instances ( Note the class is the same MyCtrl but by putting in two ng-controller="MyCtrl" you asked Angular to create two instances of MyCtrl ). So these two objects have access to two different scopes and when they are created the two different scopes are set with two different search objects. When you click on reset, the other search objects reset gets called, which means nothing happens in the first MyCtrl's scope. This is the reason why your code doesnt work as expected.
Now note that in angular services are singletons. So if you reference them in multiple places you get access to the same object. So, resetting in a different controller (instance) will still reset the same object.
Here is a plunk that works with your code.
I have no idea how angularjs works but if you put 2nd input <input type="text" ng-model="search.query"></input> near to reset button, this input will be updated.
Should inputs be inside the same div controller?
Will it help you to solve your problem?