AngularJS scope variable value change not reflecting across controllers - angularjs

In my angularjs, i have two controllers and use the variable which is referred in UI. From UI I am calling method OpenPage of NumTwoController which updates value of variable1 and NumOneController tries to access updated value.
After I update the variable in NumTwoController, newly updated value is not reflecting in NumOneController and also in NumOne.html page.
myModule.controller('NumOneController', ['$rootScope', '$scope',
function ($rootScope, $scope) {
$scope.variable1 = 1; // initial value assigned
$scope.$on('NumOne', function (e, opt) {
var valueselected = $scope.variable1; //still 1 is assigned.trying to read the value assigned in NumTwoController
});
}
]);
myModule.controller('NumTwoController', ['$rootScope', '$scope',
function ($rootScope, $scope) {
$scope.variable1 = [];
$scope.OpenPage = function (menuItem, PageReload){
$scope.variable1 = 2;
});
}
]);
I tried adding $scope.$apply() but didnt succeed.
Guidance to reflect the updated value in the another controller is much appreciated

You cannot directly access the variable of scope of one controller to another.
You can make use broadcast and on functions or angular service for sharing the scope between two controllers.
check out this =>
Share data between AngularJS controllers
https://benohead.com/blog/2016/07/18/angularjs-sharing-data-controllers/

Related

Utilising $scope.apply()

I have the following which works fine, drawing info from a RESTful api feed
app.controller('servicesController', ['$scope', '$location', '$http', '$interval',
function($scope, $location, $http, $interval) {
var getData = function() {
// Initialize $scope using the value of the model attribute, e.g.,
$scope.url = "https://(remote link to JSON api)";
$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
});
};
getData();
$interval(getData(), 10000);
}
]);
However my view is not updating every 10 seconds as expected. I have read that I need to use $scope.apply() somewhere in this above code.
I tried placing the following (in the appropriate place above)
$http.get($scope.url).success(function(data) {
$scope.listOfServices = data.runningServices; // get data from json
$scope.apply(); //I also tried $scope.runningServices.apply()
});
$scope.apply is not your problem, the scope will be digested automatically at the end of the $http request and $interval. Certain actions automatically "inform" Angular that the scope may have changed and trigger a digest; only if you're writing "non-Angular" code may you have to explicitly trigger a scope digest, since otherwise Angular wouldn't notice any changes.
No, your issue is that you're calling getData(), and then have its return value (undefined) execute every ten seconds. Which is obviously nonsense. You just want to pass the function itself to $interval:
$interval(getData, 10000);
// look ma, ^^^^^, no parentheses

Why can't I inject $scope into a factory in Angular?

I have a factory that needs to listen for a broadcast event. I injected $scope into the factory so I could use $scope.$on. But as soon as I add $scope to the parameter list I get an injector error.
This works fine:
angular.module('MyWebApp.services')
.factory('ValidationMatrixFactory', ['$rootScope', function($rootScope) {
var ValidationMatrixFactory = {};
return ValidationMatrixFactory;
}]);
This throws an injector error:
angular.module('MyWebApp.services')
.factory('ValidationMatrixFactory', ['$scope', '$rootScope', function($scope, $rootScope) {
var ValidationMatrixFactory = {};
return ValidationMatrixFactory;
}]);
Why can't I inject $scope into a factory? And if I can't, do I have any way of listening for events other than using $rootScope?
Because $scope is used for connecting controllers to view, factories are not really meant to use $scope.
How ever you can broadcast to rootScope.
$rootScope.$on()
Even though you can't use $scope in services, you can use the service as a 'store'. I use the following approach inspired on AltJS / Redux while developing apps on ReactJS.
I have a Controller with a scope which the view is bound to. That controller has a $scope.state variable that gets its value from a Service which has this.state = {}. The service is the only component "allowed" (by you, the developer, this a rule we should follow ourselves) to touch the 'state'.
An example could make this point a bit more clear
(function () {
'use strict';
angular.module('app', ['app.accounts']);
// my module...
// it can be defined in a separate file like `app.accounts.module.js`
angular.module('app.accounts', []);
angular.module('app.accounts')
.service('AccountsSrv', [function () {
var self = this;
self.state = {
user: false
};
self.getAccountInfo = function(){
var userData = {name: 'John'}; // here you can get the user data from an endpoint
self.state.user = userData; // update the state once you got the data
};
}]);
// my controller, bound to the state of the service
// it can be defined in a separate file like `app.accounts.controller.js`
angular.module('app.accounts')
.controller('AccountsCtrl', ['$scope', 'AccountsSrv', function ($scope, AccountsSrv) {
$scope.state = AccountsSrv.state;
$scope.getAccountInfo = function(){
// ... do some logic here
// ... and then call the service which will
AccountsSrv.getAccountInfo();
}
}]);
})();
<script src="https://code.angularjs.org/1.3.15/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="AccountsCtrl">
Username: {{state.user.name ? state.user.name : 'user info not available yet. Click below...'}}<br/><br/>
Get account info
</div>
</div>
The benefit of this approach is you don't have to set $watch or $on on multiple places, or tediously call $scope.$apply(function(){ /* update state here */ }) every time you need to update the controller's state. Also, you can have multiple controllers talk to services, since the relationship between components and services is one controller can talk to one or many services, the decision is yours. This approach focus on keeping a single source of truth.
I've used this approach on large scale apps... it has worked like a charm.
I hope it helps clarify a bit about where to keep the state and how to update it.

What is the difference between two scopes in the same controller (one from a service) to a directive?

I've got the below controller with two scope variables and only one passes through to my directive?
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}])
;
I've got a directive that accepts one scope but not the other?
This works
<line-chart chart-data="myData02"></line-chart>
This doesn't
<line-chart chart-data="gasFeed"></line-chart>
Do you know why?
You have to delay instantiating the directive until the data from your async service is available. Something like:
<line-chart ng-if="gasFeed" chart-data="gasFeed"></line-chart>
This should not instantiate the directive until the gasFeed scope property has data.
Try this:
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
//Create a object that will be pass in the directive, then when this variable
//it's loaded, the value in the directive (if the scope of the directive uses the '=' binding) will be updated
$scope.gasFeed = {};
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
});
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
}]);
Yes.
Here, in your example you can access gasFeed scope only when when there is a success callback from the service. Hence, till then myData02 scope will be loaded.
If you want to access both. Then try this :
.controller('newsController', ['$scope', 'gasPrices',
function($scope, gasPrices) {
gasPrices.success(function(data) {
$scope.gasFeed = data.series[0];
$scope.myData02 = [2.095,2.079,2.036,1.988,1.882,1.817,1.767,1.747];
});
}]);

pass data between controllers (service) angular

I'm creating a quiz and I want to add the answer the user gives to an array (myAnswers), when the quiz is finished, I redirect my user to the summary page, where he can see the correct answer and the answer he has given. Those are both different controllers. I tried experementing with a service, but this doesn't work out...
Can someone help me with this one please?
service
var lycheeServices = angular.module('lycheeControllers', [])
lycheeServices.service('myAnswerService', function () {
var myAnswers= [];
this.AddAnswer = function(number, a){
myAnswers[number-1] = a;
};
this.getAnswer = function(number){
return myAnswers[number-1];
};
});
controller quiz
lycheeControllers.controller('quizCtrl', ['$scope', '$http', 'myAnswerService',
function ($scope, $http, myAnswerService) {
$scope.checked = function (answer) {
myAnswerService.addAnswer(number, answer.answer);
}
controller summary
lycheeControllers.controller('summaryCtrl', ['$scope', '$http', 'myAnswerService', function ($scope, $http, myAnswerService) {
$scope.myAnswer = myAnswerService.getAnswer(number);
]
In your controller summary, when you retrieve a value using your myAnswerService.getAnswer(number);, it returns a new value and your $scope.myAnswer is a copy of the value.
If your answer is a value type, any changes on it will not affect the value in your service answer array.
If your answers array contains objects (reference type), then manipulating the properties of $scope.myAnswer will update the properties of the same object referenced by the answer inside the service's array. But if you replace it with another answer, your answer inside the answers array will not notice the change
I don't know what you're trying to achieve, but a sensible solution is you store the service object to the scope. Like this:
$scope.myAnswer = myAnswerService
Note: When you do redirects, ensure that you don't do full page refresh because your data will be cleared completely.

Update scope value when service data is changed

I have the following service in my app:
uaInProgressApp.factory('uaProgressService',
function(uaApiInterface, $timeout, $rootScope){
var factory = {};
factory.taskResource = uaApiInterface.taskResource()
factory.taskList = [];
factory.cron = undefined;
factory.updateTaskList = function() {
factory.taskResource.query(function(data){
factory.taskList = data;
$rootScope.$digest
console.log(factory.taskList);
});
factory.cron = $timeout(factory.updateTaskList, 5000);
}
factory.startCron = function () {
factory.cron = $timeout(factory.updateTaskList, 5000);
}
factory.stopCron = function (){
$timeout.cancel(factory.cron);
}
return factory;
});
Then I use it in a controller like this:
uaInProgressApp.controller('ua.InProgressController',
function ($scope, $rootScope, $routeParams, uaContext, uaProgressService) {
uaContext.getSession().then(function(){
uaContext.appName.set('Testing house');
uaContext.subAppName.set('In progress');
uaProgressService.startCron();
$scope.taskList = uaProgressService.taskList;
});
}
);
So basically my service update factory.taskList every 5 seconds and I linked this factory.taskList to $scope.taskList. I then tried different methods like $apply, $digest but changes on factory.taskList are not reflected in my controller and view $scope.taskList.
It remains empty in my template. Do you know how I can propagate these changes ?
While using $watch may solve the problem, it is not the most efficient solution. You might want to change the way you are storing the data in the service.
The problem is that you are replacing the memory location that your taskList is associated to every time you assign it a new value while the scope is stuck pointing to the old location. You can see this happening in this plunk.
Take a heap snapshots with Chrome when you first load the plunk and, after you click the button, you will see that the memory location the scope points to is never updated while the list points to a different memory location.
You can easily fix this by having your service hold an object that contains the variable that may change (something like data:{task:[], x:[], z:[]}). In this case "data" should never be changed but any of its members may be changed whenever you need to. You then pass this data variable to the scope and, as long as you don't override it by trying to assign "data" to something else, whenever a field inside data changes the scope will know about it and will update correctly.
This plunk shows the same example running using the fix suggested above. No need to use any watchers in this situation and if it ever happens that something is not updated on the view you know that all you need to do is run a scope $apply to update the view.
This way you eliminate the need for watchers that frequently compare variables for changes and the ugly setup involved in cases when you need to watch many variables. The only issue with this approach is that on your view (html) you will have "data." prefixing everything where you used to just have the variable name.
Angular (unlike Ember and some other frameworks), does not provide special wrapped objects which semi-magically stay in sync. The objects you are manipulating are plain javascript objects and just like saying var a = b; does not link the variables a and b, saying $scope.taskList = uaProgressService.taskList does not link those two values.
For this kind of link-ing, angular provides $watch on $scope. You can watch the value of the uaProgressService.taskList and update the value on $scope when it changes:
$scope.$watch(function () { return uaProgressService.taskList }, function (newVal, oldVal) {
if (typeof newVal !== 'undefined') {
$scope.taskList = uaProgressService.taskList;
}
});
The first expression passed to the $watch function is executed on every $digest loop and the second argument is the function which is invoked with the new and the old value.
I'm not sure if thats help but what I am doing is bind the function to $scope.value. For example
angular
.module("testApp", [])
.service("myDataService", function(){
this.dataContainer = {
valA : "car",
valB : "bike"
}
})
.controller("testCtrl", [
"$scope",
"myDataService",
function($scope, myDataService){
$scope.data = function(){
return myDataService.dataContainer;
};
}]);
Then I just bind it in DOM as
<li ng-repeat="(key,value) in data() "></li>
This way you can avoid to using $watch in your code.
No $watch or etc. is required. You can simply define the following
uaInProgressApp.controller('ua.InProgressController',
function ($scope, $rootScope, $routeParams, uaContext, uaProgressService) {
uaContext.getSession().then(function(){
uaContext.appName.set('Testing house');
uaContext.subAppName.set('In progress');
uaProgressService.startCron();
});
$scope.getTaskList = function() {
return uaProgressService.taskList;
};
});
Because the function getTaskList belongs to $scope its return value will be evaluated (and updated) on every change of uaProgressService.taskList
Lightweight alternative is that during controller initialization you subscribe to a notifier pattern set up in the service.
Something like:
app.controller('YourCtrl'['yourSvc', function(yourSvc){
yourSvc.awaitUpdate('YourCtrl',function(){
$scope.someValue = yourSvc.someValue;
});
}]);
And the service has something like:
app.service('yourSvc', ['$http',function($http){
var self = this;
self.notificationSubscribers={};
self.awaitUpdate=function(key,callback){
self.notificationSubscribers[key]=callback;
};
self.notifySubscribers=function(){
angular.forEach(self.notificationSubscribers,
function(callback,key){
callback();
});
};
$http.get('someUrl').then(
function(response){
self.importantData=response.data;
self.notifySubscribers();
}
);
}]);
This can let you fine tune more carefully when your controllers refresh from a service.
Like Gabriel Piacenti said, no watches are needed if you wrap the changing data into an object.
BUT for updating the changed service data in the scope correctly, it is important that the scope value of the controller that uses the service data does not point directly to the changing data (field). Instead the scope value must point to the object that wraps the changing data.
The following code should explain this more clear. In my example i use an NLS Service for translating. The NLS Tokens are getting updated via http.
The Service:
app.factory('nlsService', ['$http', function($http) {
var data = {
get: {
ressources : "gdc.ressources",
maintenance : "gdc.mm.maintenance",
prewarning : "gdc.mobMaint.prewarning",
}
};
// ... asynchron change the data.get = ajaxResult.data...
return data;
}]);
Controller and scope expression
app.controller('MenuCtrl', function($scope, nlsService)
{
$scope.NLS = nlsService;
}
);
<div ng-controller="MenuCtrl">
<span class="navPanelLiItemText">{{NLS.get.maintenance}}</span>
</div>
The above code works, but first i wanted to access my NLS Tokens directly (see the following snippet) and here the values did not become updated.
app.controller('MenuCtrl', function($scope, nlsService)
{
$scope.NLS = nlsService.get;
}
);
<div ng-controller="MenuCtrl">
<span class="navPanelLiItemText">{{NLS.maintenance}}</span>
</div>

Resources