I have a parent controller, UserEditCtrl and a child controller, EditUserCtrl. Inside of my parent controller I am pulling in a user object via a service:
userMgmtSvc.user(scope.editUserId).then(function(data) {
this.user = data;
});
Then I want to set a property of my user object to another variable.
this.selectedRoles = this.user.roles;
But this throws an error:
Cannot read property 'user' of undefined.
I'm confused as to how I reference objects that are set with this. For example, how do I just console.log the object? Because console.log('user', this.user); returns undefined:
user undefined
Here's the parent controller:
(
function (app) {
/* #fmt: off */
'use strict';
// #fmt:on
app.controller('UserEditCtrl', ['$scope', '$http', 'userMgmtSvc', 'createUserSvc', 'authSvc', '$state', '$timeout', '$location', '_',
function (scope, http, userMgmtSvc, createUserSvc, authSvc, state, timeout, location, _) {
userMgmtSvc.user(scope.editUserId.id || sessionStorage.getItem('editUser')).then(function(data) {
this.user = data;
console.log('user', this.user);
// GET states
createUserSvc.states().then(function(data) {
this.states = data;
console.log(this.states);
});
// GET countries
createUserSvc.countries().then(function(data) {
this.countries = data;
});
// GET roles
createUserSvc.roles().then(function(data) {
this.roles = data;
});
// GET insurance groups
createUserSvc.insuranceGroups().then(function(data) {
this.insuranceGroups = data;
});
this.selectedRoles = this.user.roles;
});
}]);
}(window.app)
);
This is a very basic mistake that happens when you refer to the current context with this inside a callback about which you don't know about the execution context and you end up setting values elsewhere.
In order to avoid getting into this issue, when your controller starts just set this (context of controller instance) to a variable and set everything on that. Don't assume what this is going to be.
.controller('crtl',[deps..., function(...) {
//Set this
var vm = this; //Always use this cached variable have seen a commonly used name of vm
//...............
//...............
userMgmtSvc.user(scope.editUserId).then(function(data) {
vm.user = data;
});
//...............
vm.selectedRoles = vm.user.roles
}
There are numerous other ways to do this using angular.bind, or es5 function.bind to create a bound functions (function reference pre bound with a specified context), but easiest way would be to use a cached context.
When you are using typescript you could use a => (fat arrow) syntax since typescript in ES5 mode will actually convert this.
userMgmtSvc.user(scope.editUserId).then((data) => {
this.user = data;
});
to:-
var _that = this;
userMgmtSvc.user(scope.editUserId).then((data) => {
_that.user = data;
});
Arrow functions are going to be part of the language itself (with ES6 specifications) when the engines starts supporting the arrow function syntax. So with ES6 you could safely write:-
userMgmtSvc.user(scope.editUserId).then((data) => {
this.user = data;
});
Here is an excellent answer that specifically targets this
Related
Pardon if this question is a total blow-off... Just getting warmed-up into the world angularJS.
I have these two controllers: seekerController and wizardController...
Inside the wizardController, I have a chat Scope object, and I have implemented a bunch of functions that are manipulating this chat Scope object.
Going back to the other controller now, ( seekerController ), I discover that I need to have basically a direct replica of this chat Scope object and all the other functions manipulating it as I have inside wizardController
The obvious way is just to copy all these into my other controller, and my work is done under a minute, but then I'll have a lot of repeated stuffs everywhere...
So: I'm looking for a way where I can have this(the code) in a single place, but still be able to have access to this chat Scope object from both controllers, as well as all the other functions working seamlessly.
Update - add code samples:
//seekerController
angular.module('cg.seeker', [])
.controller('SeekerController', ['$scope', 'seekerService', 'timeService', 'chatService', '$stateParams', 'toastr',
function ($scope, seekerService, timeService, chatService, $stateParams, toastr) {
...
// THE CHAT BUSINESS
$scope.chat = { close: true };
chatService.unreadCount(function(count){
$scope.chat.unreadCount = count;
$scope.$apply();
});
chatService.listDialogs( function (dialogList) {
$scope.chat.dialogList = dialogList.items;
$scope.$apply();
} );
$scope.endChat = function () {
$scope.chat.close = true;
}
$scope.chatBox = function (dialogId, occupants_ids) {
$scope.chat.opponentId = getOpponentId(occupants_ids);
chatService.getMessages( dialogId, function (messageList) {
$scope.chat.messages = messageList.items;
$scope.chat.close = false;
$scope.$apply();
});
}
var getOpponentId = function (opponentId) {
if(typeof(opponentId) != 'object') {
return opponentId;
} else {
return opponentId.filter(function(x) { return x != $scope.seeker.chat_user.chat_id_string; })[0];
}
}
$scope.sendMsg = function (opponentId) {
var msg = {
type: 'chat',
body: $scope.chat.msg,
extension: {
save_to_history: 1,
}
};
chatService.sendMsg(opponentId, msg);
$scope.chat.msg = '';
}
...
I now have an exact replica of the above code in a second controller WizardController. Exactly same, with no changes... and even a third controller have some of these, though not all.
The next level of abstraction to angularjs controllers are
Factory
Service
Provider
You could use a service called maybe chatService which could contain the common code. You can inject the service into any controller which needs the common functionality and invoke the methods on the Service.
Do note that you could use any of the above three options even though I have mentioned just Service in the above statement.
EDIT 1:
You could move the common parts of the code from Controller to Service.
For example:- You could move the construction of msg object from controller to chatService. You controller would be simply -
$scope.sendMsg = function (opponentId) {
chatService.sendMsg(opponentId);
$scope.chat.msg = '';
}
And your chatService would be doing the hard-work.
$chatService.sendMsg = function (opponentId) {
var msg = {
type: 'chat',
body: $scope.chat.msg,
extension: {
save_to_history: 1,
}
};
sendMsg(opponentId, msg);
}
After simplifying the Controllers you could revisit to see if you could use only one controller instead of 3 as they seem to be doing similar function.
I have two controllers: Controller1 and Controller2
In Controller1's $scope, I have set up all my values I need. Using the data in $scope, I'm trying to run certain functions and pass the return values to Controller2.
I was thinking about making a factory to pass variable from Controller1 to Controller2. However, I realized all input values I need lives in Controller 1. I wonder whether factory can persist the data when it runs in Controller1 and return that data when it runs again in Controller2.
Thanks
Factory is a singleton so it can be used to share data among different controllers or directives. Take a look at the fiddler here. I have created a factory 'sharedContext' which can be used to share any key-value pair across controllers using different $scope.
Factory
myApp.factory("sharedContext", function() {
var context = [];
var addData = function(key, value) {
var data = {
key: key,
value: value
};
context.push(data);
}
var getData = function(key) {
var data = _.find(context, {
key: key
});
return data;
}
return {
addData: addData,
getData: getData
}
});
From the controller that needs to share the object can call the 'addData' method of the factory to store the data under a key. The other controllers/directives which are interested in accessing the shared data can do so by calling the 'getData' method and passing the correct key.
Controller (Sharing Data)
function MyCtrl_1($scope, sharedContext) {
$scope.input_1 = 5;
$scope.input_2 = 15;
$scope.add = function() {
$scope.result = $scope.input_1 + $scope.input_2;
sharedContext.addData("Result", $scope.result)
}
}
Controller (accessing shared data)
function MyCtrl_2($scope, sharedContext) {
$scope.getData = function() {
$scope.result = sharedContext.getData("Result").value;
}
}
The only assumption here is that both the controllers need to use the exact key to share the data. To streamline the process you can use a constant provider to share the keys. Also note that I have used underscore.js to look for the key in the shared context dictionary.
This is the simplest solution that you can come up with. As you can see the factory is a simple object and because of that construct it's passed by reference not by value that means in both controller dataFactory is the same
http://plnkr.co/edit/eB4g4SZyfcJrCQzqIieD?p=preview
var app = angular.module('plunker', []);
app.controller('ControllerOne', function (dataFactory) {
this.formFields = dataFactory
});
app.controller('ControllerTwo', function (dataFactory) {
this.formData = dataFactory
});
app.factory('dataFactory', function () {
return {};
})
edit
app.factory('dataFactory', function () {
var factory = {
method1: function (arg) {
console.log('method1: ', arg)
factory.method2('called from method1')
},
method2: function (arg) {
console.log('method2: ', arg)
}
}
return factory;
})
I'm trying to expose the data obtained from the success method of a promise. In short, I don't know how to grab $scope.storedData. As it is right now, it is undefined.
genericService.js
myApp.factory('genericService', function($http){
return $http.jsonp('http://foo.com/bar.json')
.success(function(data){
return data;
})
.error(function(err){
return err;
});
});
genericController.js
myApp.controller('genericController', ['$scope','genericService',
function($scope, genericService){
genericService.success(function(data){
$scope.storeData(data);
});
$scope.storedData; // Undefined here.
$scope.storeData = function(whatever){
$scope.storedData = whatever;
}
console.log('data stored is: ', $scope.storedData); // Still undefined
}]);
How do I expose $scope.storedData to the scope outside of storeData() or genericService.success()?
Note: I don't want to use $watch. I want to overcome this scope issue fairly un-Angularly... because it should be possible.
There are 2 things I typically do:
I use models that define the expected response and will generally init my controller with an empty model.
I use a variable to track my state.
Here's an example of what my controller might look like:
myApp.controller('genericController', GenericController);
GenericController.$inject = [
'$scope',
'genericService'
];
function GenericController(
$scope,
genericService
) {
$scope.loadData = loadData;
$scope.storeData = storeData;
init();
///////////////////
function init() {
$scope.isLoaded = false;
$scope.storedData = {}; // if you use a model class, a new instance of this works best.
}
function loadData() {
genericService.success(function(data){
$scope.storeData(data);
$scope.isLoaded = true;
});
}
function storeData(whatever) {
$scope.storedData = whatever;
}
}
I cannot get a binded service value to update when it is changed. I have tried numerous methods of doing so but none of them have worked, what am I doing wrong? From everything I have seen, this seems like it should work...
HTML:
<div class="drawer" ng-controller="DrawerController">
{{activeCountry}}
</div>
Controller:
angular.module('worldboxApp')
.controller('DrawerController', ['$scope', 'mapService', function($scope, mapService) {
$scope.$watch(function() { return mapService.activeCountry }, function(newValue, oldValue) {
$scope.activeCountry = mapService.activeCountry;
});
}]);
Service:
angular.module('worldboxApp').
service('mapService', function(dbService, mapboxService, userService) {
this.init = function() {
this.activeCountry = {};
}
this.countryClick = function(e) {
this.activeCountry = e.layer.feature;
};
this.init();
});
I put a break point to make sure the mapService.activeCountry variable is being changed, but all that ever shows in the html is {}.
If you work with objects and their properties on your scope, rather than directly with strings/numbers/booleans, you're more likely to maintain references to the correct scope.
I believe the guideline is that you generally want to have a '.' (dot) in your bindings (esp for ngModel) - that is, {{data.something}} is generally better than just {{something}}. If you update a property on an object, the reference to the parent object is maintained and the updated property can be seen by Angular.
This generally doesn't matter for props you're setting and modifying only in the controller, but for values returned from a service (and that may be shared by multiple consumers of the service), I find it helps to work with an object.
See (these focus on relevance to ngModel binding):
https://github.com/angular/angular.js/wiki/Understanding-Scopes
If you are not using a .(dot) in your AngularJS models you are doing it wrong?
angular.module('worldboxApp', []);
/* Controller */
angular.module('worldboxApp')
.controller('DrawerController', ['$scope', 'mapService',
function($scope, mapService) {
//map to an object (by ref) rather than just a string (by val), otherwise it's easy to lose reference
$scope.data = mapService.data;
$scope.setCountry = setCountry; //see below
function setCountry(country) {
// could have just set $scope.setCountry = mapService.setCountry;
// however we can wrap it here if we want to do something less generic
// like getting data out of an event object, before passing it on to
// the service.
mapService.setCountry(country);
}
}
]);
/* Service */
angular.module('worldboxApp')
.service('mapService', ['$log',
function($log) {
var self = this; //so that the functions can reference .data; 'this' within the functions would not reach the correct scope
self.data = {
activeCountry: null
}; //we use an object since it can be returned by reference, and changing activeCountry's value will not break the link between it here and the controller using it
_init();
function _init() {
self.data.activeCountry = '';
$log.log('Init was called!');
}
this.setCountry = function _setCountry(country) {
$log.log('setCountry was called: ' + country);
self.data.activeCountry = country;
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="worldboxApp">
<div ng-controller="DrawerController">
<button ng-click="setCountry('USA')">USA</button>
<br />
<button ng-click="setCountry('AUS')">AUS</button>
<br />Active Country: {{data.activeCountry}}
</div>
</div>
In some case $watch is not working with factory object. Than you may use events for updates.
app.factory('userService',['$rootScope',function($rootScope){
var user = {};
return {
getFirstname : function () {
return user.firstname;
},
setFirstname : function (firstname) {
user.firstname = firstname;
$rootScope.$broadcast("updates");
}
}
}]);
app.controller('MainCtrl',['userService','$scope','$rootScope', function(userService,$scope,$rootScope) {
userService.setFirstname("bharat");
$scope.name = userService.getFirstname();
$rootScope.$on("updates",function(){
$scope.name = userService.getFirstname();
});
}]);
app.controller('one',['userService','$scope', function(userService,$scope) {
$scope.updateName=function(){
userService.setFirstname($scope.firstname);
}
}]);
Here is the plunker
Note:- In Some case if broadcast event is not fired instantly you may use $timeout. I have added this in plunker and time depends on your needs. this will work for both factories and services.
I'm attempting to use Angularjs to gather data from the USGS Earthquake feed. Typically you would need to tack ?callback=JSON_CALLBACK on to the end of the URL for Angular to use it, however the USGS feed does not recognize this option.
The URL I'm using is http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp and adding ?callback=JSON_CALLBACK (eg. http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp?callback=JSON_CALLBACK) returns a dataset wrapped in a function called eqfeed_callback.
Is there any way to use this data? I've got an eqfeed_callback function but it's not in scope which makes using Angular pointless.
Here's the code that I've got as it stands:
function QuakeCtrl($scope, $http) {
$scope.get_quakes = function() {
var url = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp';
$http.jsonp(url)
}
}
function eqfeed_callback(data) {
return data;
}
Is there any way to either get the data back into the scope, or get angular to use the eqfeed_callback function internally?
Another option would be defining the eqfeed_callback within the scope like this:
function QuakeCtrl($scope, $http) {
$scope.data = null;
$scope.get_quakes = function() {
var url = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp';
$http.jsonp(url)
}
window.eqfeed_callback = function(data) {
$scope.data = data
}
}
The only idea that comes to mind is (blech) to use a global, and then to manually trigger an Angular update, e.g.:
var callback$scope;
function QuakeCtrl($scope, $http) {
$scope.get_quakes = function() {
var url = 'http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp';
callback$scope = $scope;
$http.jsonp(url)
}
}
function eqfeed_callback(data) {
if (callback$scope) {
// 1. Use callback$scope here
// 2. Set callback$scope to undefined or null
// 3. Trigger an Angular update (since it won't be automatic)
}
}
Not pretty, but...
Expanding on #MichaelVanRijn's answer:
In order to keep the "global peace", define the global function when you need it and nullify it right after.
.controller('QuakeCtrl', function($window, $scope, $http) {
$scope.get_quakes = function() {
$window.eqfeed_callback = function(data){
console.log("quake data", data)
};
// load your jsonp data
$http.jsonp('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojsonp')
.then(function(success) {
console.log(success);
$window.eqfeed_callback = null;
}, function(fail) {
console.log(fail);
$window.eqfeed_callback = null;
})
}
})