Hello guys,
I have a page that has two instances of the same controller, the first one
is loaded with the page and the second comes from an ajax request. Inside
the controller I have a variable called filter, with initial value equal to
"status". When I try to display this variable in the first instance it
displays correctly. But when I show this variable in the second instance it
looks undefined, it shows Filter: @ {{mClerk.filter}}. The changeFilter
function works in both instances.
Anyone can help me?
My controller
app.controller('clerkCtrl', function ($scope, $http, $compile, $timeout, notifyService, DTOptionsBuilder, DTColumnBuilder) {
this.filter = 'status';
this.changeFilter = function (filter) {
this.filter = filter;
};
});
First Instance,
<div ng-controller="clerkCtrl as Clerk">
Filter: <!-- OK -->
<div class="card">
<div class="card-header">
<h2><i class="zmdi zmdi-accounts-list zmdi-hc-fw"></i> Lista</h2>
</div>
<div style="padding: 0px 20px;">
<div class="card-body table-responsive">
<table datatable="" dt-options="Clerk.dtOptions" dt-columns="Clerk.dtColumns"
class="table table-striped"></table>
</div>
</div>
</div>
</div>
Second instance, from a ajax request:
<div ng-controller="clerkCtrl as mClerk">
Filtro: <!-- FAILED -->
<button ng-click="mClerk.changeFilter('date')">Change filter</button></div>
Function that brings the page to the second instance,
$scope.loadPage = function (page) {
$http.post(page, [], $scope.config)
.then(function (response) {
$scope.modal.body = $sce.trustAsHtml(response.data.body);
$scope.modal.title = $sce.trustAsHtml(response.data.title);
$('#modalx').modal('show');
$scope.reloadPlugins();
setTimeout(function () {
$compile(angular.element('.modal-body').contents())($scope);
}, 0);
});
};
andre.figueredomultilaser.com.br's gravatar image asked Feb 17 2017 at 06:16 in Angularjs by andre.figueredomultilaser.com.br

1 Answers

Hi Andre,
If you use a controller, you get a fresh newly instantiated copy. Every
copy is a "stand alone" version. So if you change some vars in one, it will
not be reflected in another.
When you need behaviour like this, you should use a service, you inject in
both controllers. A service is a singleton. that means there is only one
copy in an AngularJS application.
For more information that explains this, read through the style guide
<https://github.com/johnpapa/angular-styleguide>.
Regards
Sander
Sander Elias 's gravatar image answered Feb 17 2017 at 21:33 by Sander Elias

Related Discussions

  • [AngularJS] In Angular 1.5 + Should All Variables Be Initialized On $onInit() in Angularjs

  • I just use the $oninit() function in my components to set variables that require api calls. Is this the appropriate way or should I move all my initialized variables into the $onInit() lifecycle hook You received this message because you are subscribed to the Google Groups "Angular and AngularJS discussion" group. To unsubscribe from this group and stop receiving emails from it, send an...

  • Why Variables Defined In Controller Does Not Update Within A Directive? in Angularjs

  • I just noticed this issue while updating/mutating objects/variables defined in a controller by a directive in the same scope. Whats missing?  Demo: http://jsfiddle.net/codef0rmer/jMUaN/ var App = angular.module('objectMutation', []);       App.controller('oneCtrl', function($scope, $timeout) {         $scope.list1 = {'name': 'AngularJS'};         $scope.list2 = [{name: 'AngularJS'}];                $...

  • Unit Testing Private Variables Of Controller in Angularjs

  • Hi everybody, I'm in a process of building my first Angular application. In most of my controllers I have a seperation between 2 kinds of data: I put data & functions that get accessed from the HTML and other controllers on the $scope. On the other hand when I declare function and data that is being used only inside the controller itself I use the var keyword because it seems unnecessary to keep...

  • [AngularJS] Accessing Factory Variables From Multiple Controllers in Angularjs

  • Hello, I'm new to angular and having trouble accessing the user from my UserFactory. My NavCtrl isn't recognizing when UserFactory.user is updated (after authentication) app.controller('NavCtrl', ['$scope', 'AuthFactory', 'UserFactory', function ($scope, AuthFactory, UserFactory) { var vm = this; vm.isLoggedIn = UserFactory.isLoggedIn; vm.isAdmin = UserFactory.isAdmin; ...

  • Is It Possible To Let Angularjs Work With Prototype Methods And Variables in Angularjs

  • Hi, everyone: I just asked a question on stackoverflow, hope to get your help: http://stackoverflow.com/questions/14397460/is-it-possible-to-let-angularjs-work-with-prototype-methods-and-variables Thank you~...

  • Watching Non-angular Variables in Angularjs

  • I suspect the answer is NO on this, but I need to ask to make sure. Can I assign a $watch on $rootScope and have it monitor a non-Angular controlled (one declared in JavaScript and not in AngularJS) variable?...

  • Asynchronous Update Of Instance Assigned To $scope Variables in Angularjs

  • Hi! As an happy developer using Angular, I have a case that would need to be shared so to find the most elegant solution. The goal: - Dynamically create an instance of an object which is then assigned to a $scope variable. - Later on (after having received answers from the server), update the content of this instance, without using $scope. - The trick would be to hide the details of the object ...

  • Working With Variables In Angular, Please Help in Angularjs

  • Hello, I'm using angular repeat like this:                                                                                     {{menuItem.Title}}                                                     Now if I open address #/Processes all lists have class selected. I would like to add class selected only on item that have menuItem.urlPart property same as actual page address. I tryed something...

  • Passing Variables Into A Directive Does Not Work When The Template Is Remote. in Angularjs

  • http://jsfiddle.net/nemesarial/mKjwx/19/ This works perfectly fine. When you move the directive template into a remote resource (templateUrl declaration), the interpolation happens correctly in the directive attributes, but those values are not passed on to the directive template. ...

  • Each Person Using App Shares The Same Controller Variables in Angularjs

  • Hello everyone, I'm fairly new to Angular and I guess I'm not understanding why this is happening... My issue is that when I have two browsers open, whether its on the same computer or separate computers, any time I enter anything in say a text box, that same input is then displayed in all the browsers text boxes. I do have two-way binding, but I didn't think this would extend to binding these variables...

  • Changing Controller-level Variables Inside An Ng:repeat Doesn't Work... in Angularjs

  • In the process of debugging this I found a work-around.  I just find this kind of strange: http://jsfiddle.net/vBDQv/ If you click on "Inside Data2", nothing happens.  If you run a debugger and step through the code, it looks like it's doing what it's supposed to: assigning this.data to this.data2.  Before it makes the assignment, this.data is data1, as it should be.  However, after it makes the...

  • DynamicComponentLoader.loadAsRoot - Variables Not Bound in Angularjs

  • I'm trying to migrate to Angular 2.0. and I hit the wall when trying to use it with an external visualization library (Visjs). I can provide custom templates for elements that Visjs is displaying but those aren't processed by Angular at that moment. I was trying to generate ids for those elements and load them using DynamicComponentLoader.loadAsRoot method but it seems that none of the variables that...

  • Variables in Angularjs

  • Hi all, I have 3 controllers and I want a common variable in them. For example, controllerA, controllerB and controllerC. If I have a variable $scope.projects, if I update this in controllerA it should also reflect in controllerB. How do I go about doing this? Thank you Bhushan...

  • Globar Variables Without Ng-app Or Ng-controller In Parent Element in Angularjs

  • Hi, I'm trying to make an angular app by bootstrapping it with main module like this: angular.element(document).ready(function() {   angular.bootstrap(document, [     mainModule.name   ], {     strictDi: true   }); }); so I don't have ng-app or any ng-controller in "root" view (index.html). I have made an myLogin directive which receive url attribute for authentification backend API, and global...

  • What Is The Recommended Angular Way To Pass Variables Such As Ids In Via Hyperlinks? in Angularjs

  • What is the recommended Angular way to pass variables like ids in via links so that they can be used to fetch $resource details? It seems as if there is probably a recommended way to do this in services.js and controllers.js that doesn't involve passing query parameters.  //index.html ID1 ID2 //services.js   $route.when('/myapp', {template: 'partials/myapp.html', controller: AppController}); //How...

  • Variables In Templates Not Displaying IE8 in Angularjs

  • I've outlined the problem here: http://stackoverflow.com/questions/13464501/angularjs-data-binding-templating-not-working-in-ie-8 Basically any {{variables}} in my HTML templates aren't rendering in IE8 but work fine in Chrome and Firefox. I've searched but haven't really found any information on fixing this issue. Can someone assist or point my to a resource I may have overlooked?...

  • Declaration Of Scope Variables In The View? in Angularjs

  • How do people feel about the fact that in angular views, one can just assign to an unknown variable in the view and a scope property is created automatically? I love the simplicity, but hate when it it burns me due to a typo or an assignment made in the wrong scope. Examples: 1) in the code below when the link is clicked on a new "foo" scope variable is created and 23 is assigned to it.   click...

  • How Do You Correctly Minify / Allow For Dependency Injection For Variables Passed To A Controller In A Resolve Block in Angularjs

  • Below is my code, but when passing crew to the controller it is failing. I get error, "Service name expected". I need to figure out how to do this so I can minify my code. Any help is appreciated! var app = angular.module('app', ['starTrekServices']); app.config(function ($locationProvider, $routeProvider) {     $routeProvider.when("/", {templateUrl:"partials/home.html"});     $routeProvider...

  • ForEach Affecting Variables It Should Not Be Affecting in Angularjs

  • Hello friends. I have come across a situation when using angular.forEach, I am seeing very strange results. It seems the forEach is setting the value of other variables it should not be setting. I also came across 2 other problems which I have clearly described in the attached fiddle. Might make sense to look at them in reverse order. Please have a look: http://jsfiddle.net/WArxJ/23/ Thanks ...

  • Why Andular Update Variables Not Related To Each Other? in Angularjs

  • Hi I've created small jsfiddle to describe this: http://jsfiddle.net/dmitrysh/Y2ANR/ click on "click me" button As you can see myField gets updated, but it shouldn't because nothing change it. Please give me some info on this angular behaviour, because this is completely unclear for me. Thanks...