calling a function on url call in angularjs - javascript

I am very new to angularjs and require help on calling a function on url call.
I am directly accessing the query params from url using
http://localhost/index.html#/?defined=true&var1=value1&var2=value2&
$location.search()['defined'];
now , within my controller I have a function 'caller' which is being called on events like ng-change , ng-model etc. on the html page which works fine
angular.module('ngAp').controller
('ngCntrl',function($scope,$http,$location{
$scope.caller = function() {
// code logic
}
}
What I am trying to do is to call the function 'caller' when I directly access the above url
$location.search()['defined'];
if (defined == "true" )
{ //call the caller function.
}
I have no idea how can I call the function when i directly call the url.
Any help is greatly appreciated.

If you take a look at the docs for $location - https://docs.angularjs.org/api/ng/service/$location
It has some events you can use like $locationChangeStart. But it's better to bind to this event in angular.module('ngAp').run(...).
angular.module('ngAp').run(moduleRun);
function moduleRun ($location, $rootScope) {
$location.on('$locationChangeStart', function (event, newUrl, oldUrl, newState, oldState) {
var defined = $location.search()['defined'];
$rootScope.defined = defined //you can assign it to $rootScope;
if (defined === "true" ) {
//call the caller function.
}
})
}

Related

Angular Material $mdPanel doesn't have a close() method

I am using angular material $mdPanel, i can display it using the open() method but i can't remove it (using close button like the demo). The documentation is not clear about that, the close method doesn't work. Is there any solution for that ?
$mdPanel documentation
When you call $mdPanel.open(), it returns a promise. The call to the promise contains a reference to the created panel. You can call close() on that.
$res = $mdPanel.open(...);
$res.then(function(ref) {
$scope.ref = ref;
})
Later on, to close, call:
$scope.ref.close();
There is no close() method on $mdPanel it is instead a method on the panel reference, which is passed on the first argument to the controller for that panel. So to be able to close the panel you need to pass a controller function in your panel definition similar to below.
Hope this helps!
var config = {
...,
controller: PanelController,
controllerAs: 'panelCtrl',
template: '<div><div>Some content</div><button ng-click="panelCtrl.close()">Close</button></div>',
...
};
function PanelController(panelRef) {
this.close = function () {
panelRef && panelRef.close();
};
}
You can inject the mdPanelRef inside a controller and then call mdPanelRef.close()
var config = {
...,
controller: PanelController
};
function PanelController(mdPanelRef) {
this.close = function () {
mdPanelRef.close();
};
}

How to call an anonymous function stored as a string

I am trying to dynamically set page title in AngularJs.
I'm using angular-ui router and stateHelper.
So I have this in my main template:
<title ng-bind="pageTitle"></title>
And this in my ui-router:
{
name: 'show',
url: '/:id',
title: function($stateParams){
return 'Showing '+$stateParams.id;
}
}
Then this:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams)
{
//set page title
if(angular.isFunction(toState.title))
{
var callBack = toState.title; //this is the anonymous function
//I expect the anonymous function to return the title
$rootScope.pageTitle = callBack;
}else{
$rootScope.pageTitle = toState.title;
}
}
The Challenge:
var callBack = toState.title;
returns a string like this "function($stateParams){return 'Showing '+$stateParams.id;}"
How do I execute this function and also respect the parameters dependency injected parameters passed along with it (unknown number of DI)
NB: I am so scared of eval and wouldn't like to use it :(
A function can be invoked with relevant dependencies with $injector.invoke:
$rootScope.$on('$stateChangeStart', function(event, toState, toParams)
{
if(angular.isFunction(toState.title) || angular.isArray(toState.title))
{
$rootScope.pageTitle = $injector.invoke(toState.title);
}else{
$rootScope.pageTitle = toState.title;
}
}
As any other DI-enabled function, title should be annotated accordingly, it may be either a function or an array.
You can inject $stateParams into the controller (where the $rootScope.$on statement in) first, and call
toState.title($stateParams);
By the way, you can consider use a better solution to handle "dynamic title". Check the way this project use: https://github.com/ngbp/ngbp

The service call is returning the function definition than the actual return in angular

Here in summary.controller.js at line 37 i'm calling the 'filter.jdpa' which is the method defined in the service: filter.js.
The method is meant to return an array jdpaarr but when i call it in the controller i get the whole method definition as the output
The code for the service is also attached below
(function () {
'use strict';
angular.module('app')
.service('filter', filter);
function filter() {
this.jdpaf=jdpaf;
this.yearf=yearf;
this.cityf=cityf;
function jdpaf(){
var jdpaarr=['All','JDPA','Non-JDPA'];
console.log(jdpaarr);
return 'jdpaarr';
}
function yearf(){
var yeararr=['2011','2012','2013','2014'];
console.log(yeararr);
return 'yeararr';
}
function cityf(){
var cityarr=['Delhi','Mumbai','Trivandrum','Banglore','Hyderabad'];
return cityarr;
}
}
})();
I have given console.logs in the service itself but that fails to work.
But why is the whole function definition being shown in the function call ?
You are basically assigning the definition only.
Try calling/executing it on initialization and saving the returned value in your scope like.
$scope.Filterarray.jdpa = filter.jdpaf();
Hope this helps.

$.getJSON call from angular.element(document).ready or initController

I am using the following snippet to get the data from server to load the initial content of the page.
(function () {
'use strict';
angular
.module('app')
.controller('MyController', MyController);
MyController.$inject = ['UserService', '$rootScope', '$scope', '$cookieStore', 'AuthenticationService'];
function MyController(UserService, $rootScope, $scope, $cookieStore, AuthenticationService) {
/*Discussion Board related Functions*/
angular.element(document).ready(function () {
// Get Current User
$rootScope.globals = $cookieStore.get('globals') || {};
$scope.currentUser = AuthenticationService.GetAuthData($rootScope.globals.currentUser.authdata);
$.getJSON(
"http://localhost/getSomeServerData.php",
{ userName: $scope.currentUser },
$scope.getSomeDataResponse
);
});
$scope.getSomeDataResponse = function (jason) {
var servRet = jason;
alert("On Load Called-2");
};
}
})();
However, the response function $scope.getSomeDataResponse is not getting called.
Please let me know what is wrong with this approach.
However, the response function $scope.getSomeDataResponse is not
getting called.
Please let me know what is wrong with this approach.
The issue is, you are referencing getSomeDataResponse before it is being declared. Also, you are using jQuery's getJSON() to get the data from server using HTTP GET request in your angularJS code.
This is particularly not a recommended practise. If you include jQuery in your page, AngularJS will use jQuery instead of jqLite when wrapping elements within your directives, otherwise it'll delegable to jqLite(which might not work in all cases). To be at a safer side, use angular's $http.get() service instead of $.getJSON()
$http.get("http://localhost/getSomeServerData.php",{ userName: $scope.currentUser})
.then(function(jason){
//success handler function
var servRet = jason;
alert("On Load Called-2");
},function(err){
//error handler function
alert(err);
})
Ofcourse you'd need to inject $http service in your controller to make it work. Have a look at this thread for other possible alternatives.
Cheers!
First, you have to define your result function before using.
Second, you have to use $.getJSON correctly. So this worked for me after fixing
$scope.getSomeDataResponse = function (jason) {
var servRet = jason;
alert("On Load Called-2");
};
/*Discussion Board related Functions*/
angular.element(document).ready(function () {
// Get Current User
$rootScope.globals = $cookieStore.get('globals') || {};
$scope.currentUser = AuthenticationService.GetAuthData($rootScope.globals.currentUser.authdata);
$.getJSON(
"http://localhost/getSomeServerData.php",
{ userName: $scope.currentUser }
).always($scope.getSomeDataResponse);
the callback method was different in jQuery. use fail and done callbacks by looking at the jQuery documentation
http://api.jquery.com/jquery.getjson/

Loading one dataset using data from another in Angular $watch

I am creating a messaging service that needs to do the following 1.) Load a messsage from our messages service, get the recipient's ids, and then load the recipients' info from a users service. I've tried both using the messages service callback, and also creating a watcher on the message object, without much success. The service works, but it doesn't assign the result to the $scope correctly. Here's the controller. All of the services are working correctly:
function MessageCtrl ($scope, $http, $location, $routeParams, Messages, Members) {
if ($routeParams.mid) { // Checks for the id of the message in the route. Otherwise, creates a new message.
$scope.mid = $routeParams.mid;
$scope.message = Messages.messages({mid: $scope.mid}).query();
$scope.$watch("message", function (newVal, oldVal, scope) {
if (newVal.data) {
$scope.recipients = Members.members({uids: newVal.data[0].uids}).query();
}
}, true);
} else {
$scope.create = true;
}
// Events
$scope.save = function () { };
$scope.preview = function () { };
$scope.send = function () { };
}
The correct way to use query is to perform the action in the callback that is passed in query function. In other words$scope.message should be assigned in the callback. Also you don't need a $watch. You can call the other service within the callback directly. But to keep it clean please use deferred
http://docs.angularjs.org/api/ngResource.$resource
http://docs.angularjs.org/api/ng.$q

Categories