How do I add result to my scope ng-click? - javascript

This is a relatively simple piece of code that calls a service and returns some data. I need to set the $scope with the result of the data. Is there an easy way to set this data to the scope without resorting to to binding the scope to the function in the then clause?
Angular Code
(function () {
var app = angular.module('reports', []);
var reportService = function($http, $q) {
var service = {};
service.getMenuData = function() {
var deffered = $q.defer();
$http.get('/Report/MenuData').success(function(data) {
deffered.resolve(data);
}).error(function(data) {
deferred.reject("Error getting data");
});
return deffered.promise;
}
return service;
};
reportService.$inject = ['$http', '$q'];
app.factory('reportService', reportService);
var reportMenuController =
function ($scope, $http, reportService) {
$scope.getMenuData = function(e) {
reportService.getMenuData().then(function(data) {
// Need to set the $scope in here
// However, the '$scope' is out of scope
});
}
};
reportMenuController.$inject = ['$scope', '$http', 'reportService'];
app.controller('ReportMenuController', reportMenuController);
})();
Markup
<div>
<div ng-controller="ReportMenuController">
<button ng-click="getMenuData()">Load Data</button>
</div>
</div>

There is absolutely no problem to set the $scope from within the function passed to then(). The variable is available from the enclosing scope and you can set your menu data to one of its fields.
By the way: You should consider to use then() instead of success() for your http request. The code looks much nicer because then() returns a promise:
service.getMenuData = function() {
return $http.get('/Report/MenuData').then(function(response) {
return response.data;
}, function(response) {
deferred.reject("Error getting data");
});
}
success() is deprecated by now.

I didn't notice the small detail missing in the plunker where my code was different.
(function () {
...
var reportMenuController =
function ($scope, $http, reportService) {
$scope.getMenuData = getMenuData;
function getMenuData(e) {
reportService.getMenuData().then(function(data) {
// Now I have access to $scope
});
}
};
...
})();
Notice the changes to the two lines as below:
$scope.getMenuData = getMenuData;
function getMenuData(e) {
This also begs a small question which is, "Why is it okay to set getMenuData to the $scope before it is declared?

Related

AngularJS - $q undefined in a directive

I'm trying to inject $q into my directive, but though $q is defined as a resolver() at first, when calling the function it is undefined. Maybe something related to binding? I don't know.
(function () {
'use strict';
myForm.$inject = ["$q"];
angular
.module('myModule')
.directive('myForm', myForm);
function myForm($q) {
return {
restrict: 'EA',
scope: {
ngSubmitFunction: '&',
},
templateUrl: 'myTemplate',
controllerAs: 'ctrl',
controller: ["$scope", "$window", "$q", function ($scope, $window, $q) {
var vm = this;
vm.name = 'myForm';
$scope.submitPromise = function(){};
vm.ngSubmit = ngSubmit;
function ngSubmit($form) {
vm.submitDisabled = true;
$form.$setSubmitted();
if ($form.$valid) {
$scope.submitPromise().then(function() {
vm.submitDisabled = false;
});
}
}
}],
link: function (scope, element, attrs) {
console.log($q);
scope.submitPromise = function($q) {
console.log($q);
var deferred = $q.defer();
scope.ngSubmitFunction();
return deferred.promise;
}
}
};
}
}());
The objective is to call ngSubmit when user clicks on a button. ngSubmit disables the button, waits for the async calls to be over and then enables the button.
In the example code, the 1st console.log($q) (executed when loading the page) outputs this:
Q(resolver) {
if (!isFunction(resolver)) {
throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
}...
Which to me looks like correct.
But when calling submitPromise() after pressing the button, this is the output:
undefined
TypeError: Cannot read property 'defer' of undefined
When is $q lost?
Note: this is not the only version I tried, originally all code was on controller, nothing on link. I've also been told this pattern is deprecated and to use this one, which is better:
function submitPromise($q) {
return $q(function (resolve) {
$scope.ngSubmitFunction();
})
}
Nothing worked. Everything produces the same error, $q gets undefined at some point and can't find out why.
Using $q as an argument parameter is causing $q to become undefined.
myForm.$inject = ["$q"];
angular
.module('myModule')
.directive('myForm', myForm);
function myForm($q) {
return {
link: function (scope, element, attrs) {
console.log($q);
//scope.submitPromise = function($q) {
//Remove $q as parameter
scope.submitPromise = function() {
console.log($q);
var deferred = $q.defer();
//scope.ngSubmitFunction();
deffered.resolve(scope.ngSubmitFunction());
return deferred.promise;
}
}
The myForm function is a directive construction function to which the AngularJS framework will inject service providers. But the submitPromise function is not injectable; it is a child function of myForm. All injections should be done in the parent function.
Also the code can be simplified by using $q.when to create a promise.
link: function (scope, element, attrs) {
console.log($q);
//scope.submitPromise = function($q) {
//Remove $q as parameter
scope.submitPromise = function() {
console.log($q);
return $q.when(scope.ngSubmitFunction());
}
}
You should solve with this different injection
(function () {
'use strict';
angular
.module('myModule')
.directive('myForm', ['$q', function($q){
return {
. . .
}
}]);
Hope I've been helpful.
The right code is ( I removed parameter from function declaration ):
$scope.submitPromise=function() {
return $q(function (resolve) {//$q is available in function declared in the same scope
$scope.ngSubmitFunction();
});
}
Above code use $q variable from scope ( javascript scope not angular $scope ), $q is visible for all functions declared inside myForm function.
Your previous code used function parameter not $q from scope, parameter was not passed, so was undefined.
Javascript scope means everything between open tag { and close tag }. Check this example:
function(y){//scope start
var x; //scope local variable
var someFunc=function(){
//here is available y and x variables
};
//scope end
}
//outside of scope - here variables x and y not exists

Update $scope inside .then?

I have a function inside a controller and I'm confused as to how to update a $scope variable from inside a .then function.
Heres my function:
searchSpotify(query, $scope) {
this.Spotify.search(query,'track').then(function (data) {
console.log(data.tracks.items); // this is working
$scope.result = data;
});
}
In the console log I receive this error:
TypeError: Cannot set property 'result' of undefined
Do I use $scope.$apply somehow?
EDIT:
Here's the entire controller for context
(function() {
class SelectionController {
constructor(User, groupService, selectionService, songService, $scope, $routeParams, Spotify) {
this.groupId = $routeParams.groupId;
this.selectionId = $routeParams.selectionId;
this.groupService = groupService;
this.selectionService = selectionService
//this.selections = this.selectionService.getSelections();
this.songService = songService;
this.searchResults;
this.$scope = $scope;
this.Spotify = Spotify
}
searchSpotify(query) {
this.Spotify.search(query, 'track').then(function(data) {
console.log(data.tracks.items);
$scope.result = data;
});
}
addSong(name, artist, album) {
alert('called from selection controller');
this.songService.addSong(this.selectionId, name, artist, album);
}
createSelection(name, description) {
this.selectionService.createSelection(this.groupId, name, description);
}
deleteSelection(selection) {
this.selectionService.deleteSelection(selection);
}
}
angular.module('songSelectionApp')
.controller('SelectionController', SelectionController);
})();
Save reference to $scope:
searchSpotify(query) {
var $scope = this.$scope;
this.Spotify.search(query, 'track').then(function(data) {
console.log(data.tracks.items);
$scope.result = data;
});
}
Or use arrow functions:
searchSpotify(query) {
this.Spotify.search(query, 'track').then((data) => {
console.log(data.tracks.items);
this.$scope.result = data;
});
}
.bind(this) should also work, as another answers suggest.
Regarding $scope.$apply: you need it only when you want to change a $scope outside of a $digest, for example when you use external (non-angular) libraries/functions, like WebSocket, or jquery event listeners. Untill Spotify is an angular service/factory - you don't need $scope.$apply
From docs:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
this.Spotify.search(query,'track').then(function (data) {
console.log(data.tracks.items); // this is working
this.result = data;
}.bind($scope));
Should be all you need really. You are basically telling the internal scope what this should really be
You should use
this.Spotify.search(query,'track').then(function (data) {
console.log(data.tracks.items); // this is working
this.$scope.result = data;
}.bind(this));

Loading view configuration

I would like to do something like this:
app.config(function($routeProvider){
$routeProvider.when('products/list', {
controller: 'ProductListCtrl',
templateUrl : 'products/list/view.html',
resolve : { data : function(){
...
},
loadingTemplateUrl : 'general/loader.html'
}
});
I would like to have the loading page in a different view.
This would make the code in the view and controller of every page cleaner, (no <...ng-include ng-show="loading"...>). This would also mean that I don't have to $scope.$watch the data for changes. Is there a clean solution to do something similar (not necessarily in the .config method) or an alternative library to do this?
Assuming you want to show some general template for all state transitions while the data is resolved, my suggestion is to listen to the events fired by the routing library. This allows to use one central point to handle all state transitions instead of polluting the routing config (which I think will not be that easy to do).
Please see the docs for $routeChangeStart, $routeChangeSuccess and of course $routeChangeError at the angular router docs
Maybe someone could be interested in what I did: I created a new service and a new view directive. It could seem like a lot of work, but doing this was much easier than I had expected. The new service enables me to separate the main view from the loading view, that I could reuse in all pages of the application. I also provided the possibility to configure an error template url and error controller, for when the loading failed.
The Angular $injector, $templateRequest and $controller services do most of the work. I just had to connect a directive, that depends on these services, to the right event ($locationChangeSuccess), and to the promise, retrieved (using $q.all) from the resolve object's functions. This connection was done in the route service. The service selects the right template url and comtroller, and passes it on for the directive to handle.
A shortened version (with the getCurrentConfig method left out):
RouteService:
(function () {
'use strict';
// provider:
angular.module('pikcachu')
.provider('pikaRouteService', [function () {
var routeConfigArray;
var otherwiseRouteConfig;
//configuration methods
this.when = function (url, routeConfig){
routeConfigArray.push({url: url, routeConfig: routeConfig});
return this;
}
this.otherwise = function(routeConfig){
otherwiseRouteConfig = routeConfig;
return this;
}
// service factory:
this.$get = ['$rootScope', '$location', '$q', '$injector', '$templateRequest',
function ($rootScope, $location, $q, $injector, $templateRequest) {
function RouteService() {
this.setViewDirectiveUpdateFn = function(){ /*...*/ }
function init(){
$rootScope.$on('$locationChangeSuccess', onLocationChangeSuccess);
}
function onLocationChangeSuccess(){
// get the configuration based on the current url
// getCurrentConfig is a long function, because it involves parsing the templateUrl string parameters, so it's left out for brevity
var currentConfig = getCurrentConfig($location.url());
if(currentConfig.resolve !== undefined){
// update view directive to display loading view
viewDirectiveUpdateFn(currentConfig.loadingTemplateUrl, currentConfig.loadingController);
// resolve
var promises = [];
var resolveKeys = [];
for(var resolveKey in currentConfig.resolve){
resolveKeys.push(resolveKey);
promises.push($injector.invoke(resolve[resolveKey]));
}
$q.all(promises).then(resolveSuccess, resolveError);
function resolveSucces(resolutionArray){
// put resolve results in an object
var resolutionObject = {};
for(var i = 0; i< promises.length;++i){
resolved[resolveKeys[i]] = resolutionArray[i];
}
viewDirectiveUpdateFn(currentConfig.errorTemplateUrl, currentConfig.errorController);
}
function resolveError(){
viewDirectiveUpdateFn(currentConfig.errorTemplateUrl, currentConfig.errorController);
}
}
}
init();
}
return new RouteService();
}]
})();
View directive
(function () {
'use strict';
angular.module('pikachu')
.directive('pikaView', ['$templateRequest', '$compile', '$controller', 'pikaRouteService', function ($templateRequest, $compile, $controller, pikaRouteService) {
return function (scope, jQdirective, attrs) {
var viewScope;
function init() {
pikaRouteService.listen(updateView);
}
function updateView(templateUrl, controllerName, resolved) {
if(viewScope!== undefined){
viewScope.$destroy();
}
viewScope = scope.$new();
viewScope.resolved = resolved;
var controller = $controller(controllerName, { $scope: viewScope });
$templateRequest(templateUrl).then(onTemplateLoaded);
function onTemplateLoaded(template, newScope) {
jQdirective.empty();
var compiledTemplate = $compile(template)(newScope);
jQdirective.append(compiledTemplate);
}
}
init();
};
}
]);
})();

Karma testing a call to a function inside a scope.function

I have a UploadDocumentCtrl.js where i am accessing a service call to a function inside another function . This outer function is bound to the scope . My problem is i am unable to access the code statements inside this (Code block C) . I want to access the 'flag' variable and check if that is true . Can anyone point me in the correct direction or tell me what i am doing wrong here ? Thanks ..
UploadDocumentsCtrl.js
(function () {
'use strict';
angular.module('myApp')
.controller('UploadDocumentsCtrl', UploadDocumentsCtrl);
UploadDocumentsCtrl.$inject = ['$rootScope', '$scope', '$modalInstance', '$window', 'companyService'];
function UploadDocumentsCtrl($rootScope, $scope, $modalInstance, $window, companyService) {
$scope.onFileSelect = onFileSelect;
$scope.buttonDisabled = false;
function onFileSelect(files) {
//Can access the code here
function upload(file) {
//Can access the code here as well
companyService.uploadDocuments(file)
.success(function (data, status, headers, config) {
// Code block C
// Cannot access any code here or the error code block below
$scope.flag = true;
})
.error(function (data, status, headers, config) {
});
}
files.forEach(function (file) {
file.progress = 0;
file.percent = 0;
$scope.filesToUpload.push(file);
upload(file);
});
}
}
})();
Jasmine test case
(function () {
"use strict";
describe('UploadDocumentsCtrl', function () {
var scope, companyService,companyControllerFactory;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function($rootScope, $controller , _companyService_) {
companyService = _companyService_;
scope = $rootScope.$new();
companyControllerFactory = function(){$controller('UploadDocumentsCtrl',
{
$scope: scope,
companyService: _companyService_
});
};
}));
describe("onFileSelect", function() {
it(" Should make the flag to true ", function() {
var files = [{}];
companyControllerFactory();
spyOn(companyService, 'uploadDocuments').and.returnValue({ success: function(){}});
scope.onFileSelect(files);
expect(scope.flag).toBe(true);
});
});
});
})();
The error i am getting while trying to do the above..
1) Should make the flag to true
UploadDocumentsCtrl onFileSelect
TypeError: companyService.uploadDocuments(...).success(...) is undefined in http://localhost:9876/absoluteC:/Users
/Documents/fle/Fle/WebApiRole/app/company/UploadDocumentsCtrl.js?f11d5dcacbf2ca1d63778bfa04c582862e325523
( line 31)
upload#http://localhost:9876/absoluteC:/Users/Documents/fle/Fle/WebApiRole/app/company/UploadDocumentsCtrl
.js?f11d5dcacbf2ca1d63778bfa04c582862e325523:31:17
onFileSelect/<#http://localhost:9876/absoluteC:/Users/Documents/fle/Fle/WebApiRole/app/company/UploadDocum
entsCtrl.js?f11d5dcacbf2ca1d63778bfa04c582862e325523:51:17
onFileSelect#http://localhost:9876/absoluteC:/Users/Documents/fle/Fle/WebApiRole/app/company/UploadDocumen
tsCtrl.js?f11d5dcacbf2ca1d63778bfa04c582862e325523:46:13
#http://localhost:9876/base/test/company/UploadDocumentsCtrlSpec.js?c5db561e203bdfae1a6f7509347d3f7032e8f785:35:17
In my project I am using below format to spy service. You can try below option:
var deffered = q.defer();
spyOn(companyService, 'uploadDocuments').and.returnValue(deffered.promise);
deffered.resolve();
And to apply this you will have to use $rootScope.$apply() before assert (i.e. before expect())
Is companyService making an http call?
If so, you'll need to mock the response with $httpBackend and then get to the proper conditions based on the mocked response using $httpBackend.flush().

Using deeply nested object from JSON in AngularJS - strange behavior

I'm trying to understand how AngularJS sees an object from a deeply nested JSON. Here's an example plunker. The data comes from service and is assigned to $scope.data. The javascript code seems to want me to declare every level of the object first before usage, but referencing a deep level within object from the view HTML always works, and using the deep level in a function kinda works. It's rather inconsistent.
I'm not sure if my understanding of $scope is lacking, or if this has something to do with promise objects. Advise please?
HTML
<body ng-controller="MainCtrl">
Referencing nested obj in view works:
{{data.level1.level2}}
<br>
Using nested obj within declared scope var doesn't work:
{{nestedObj}}
<br>
Using nested obj in a function works but throws TypeError:
{{getLen()}}
</body>
Javascript
var app = angular.module('app', []);
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
$http.get(jsonURL).success(function (data, status) {
scope.data = data;
});
}};
});
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope);
// Using nested obj within declared scope var doesn't work
// Uncomment below to break whole app
// $scope.nestedObj = $scope.data.level1.level2;
// Using nested obj in a function works but throws TypeError
// Declaring $scope.data.level1.level2 = [] first helps here
$scope.getLen = function () {return $scope.data.level1.level2.length};
});
JSON
{
"level1": {
"level2": [
"a",
"b",
"c"
]
}
}
Your $http request is asynchronous.
app.controller('MainCtrl', function($scope, JsonSvc) {
JsonSvc.read('data.json', $scope);
//$scope.data.level1.level2 doesn't exist yet at this point in time
//and throws an exception
$scope.nestedObj = $scope.data.level1.level2;
//$scope.data.level1.level2 doesn't exist yet at this point in time
//and throws an exception
//once Angular does dirty checking this one will work since the
//$http request finished.
$scope.getLen = function () {
return $scope.data.level1.level2.length
};
});
Since you have three scope objects that rely on that data it would be best to assign those in the call back.
app.factory('JsonSvc', function ($http) {
return {read: function(jsonURL, scope) {
$http.get(jsonURL).success(function (data, status) {
scope.data = data;
scope.nestedObj = scope.data.level1.level2;
scope.getLen = function () {
return scope.data.level1.level2.length;
};
});
}};
});
If you do not want to set it all up on the call back, you could also use $broadcast() and $on()
app.factory('JsonSvc', function ($http, $rootScope) {
return {
read: function (jsonURL, scope) {
$http.get(jsonURL).success(function (data, status) {
scope.data = data;
$rootScope.$broadcast("jsonDone");
});
}
};
});
app.controller('MainCtrl', function ($scope, JsonSvc) {
JsonSvc.read('data.json', $scope);
$scope.name = "world";
$scope.$on("jsonDone", function () {
$scope.nestedObj = $scope.data.level1.level2;
$scope.getLen = function () {
return $scope.data.level1.level2.length;
};
});
});
Ray, another option is to return the $http.get call since its a promise and use the .then() function to declare $scope.nestedObj or anything else you want to do with data once it returns.
Here's my example: http://plnkr.co/edit/GbTfJ9
You can read more about promises in Angular here: http://docs.angularjs.org/api/ng.$q

Categories

Resources