I have a strange thing:
my controller works, but getHash service is called on loading, instead on calling saveit()
function on index html:
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope','$http','getHash', function ($scope,$http, getHash) {
$scope.keys = getHash.get(function(keys) {
$scope.key = keys.key;
});
$scope.saveit = function () {
$scope.formData = {
'key' : $scope.key
};
console.log ($scope.formData);
//Do Something with formData
}
}
This Example is not working, the $scope.key
is empty, but the getHash
Service is called as it should.
angular.module('myApp.controllers', [])
.controller('MyCtrl', ['$scope','$http','getHash', function ($scope,$http, getHash) {
$scope.saveit = function () {
$scope.keys = getHash.get(function(keys) {
$scope.key = keys.key;
});
$scope.formData = {
'key' : $scope.key
};
console.log ($scope.formData);
//Do Something with formData
}
}
Has anyone an explanation for this behavior? how can i get $scope
in the function saveit
?
or save variables to $scope
inside saveit
?
Thanks, Patrick
$scope.keys
executes on load because it's calling what looks like a service. And since it's never called from withinsaveit()
it obviously doesn't get called when you executesaveit()
. In the second case$scope.keys
is run, but due to it's asynchronous nature the program continues onto$scope.formData
and doesn't wait forgetHash.get(function(keys)
to finish executing. The following might work better for you:$scope.keys = getHash.get(function(keys) { $scope.key = keys.key; $scope.formData = { 'key' : $scope.key }; });
Also a plunker would be helpful. – winkerVSbecks Jul 27 '13 at 1:54