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