How can I call/access Controller method ($scope.some_function()) after finished Ajax request!
var app = angular.module('home', ['ngRoute']);
app.controller('IModalCtrl', function ($scope, $http, $route, $routeParams, $location) {
$scope.will_call_this = function() {
//
};
});
app.config(['$routeProvider', '$locationProvider', '$httpProvider',
function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/news/:cat/:slug/:id', {
templateUrl: function (attr) {
return '/news/' + attr.cat + '/' + attr.slug + '/' + attr.id + '?ajax=1'
},
controller: 'IModalCtrl'
// IS ANY PROPERTY/METHOD HERE
// WHICH WILL ALLOW/ACCESS TO CONTROLLER PROPERTY
})
.otherwise('/');
}]);
In above, I want to call IModalCtrl's $scope.will_call_this() function after $routeProvider has finished the request. Just like jQuery ajax work.
jQuery Ajax e.g:
jQuery.ajax("example.php")
.done(function () {
alert("success");
// Need this functionality in AngulaJS
})
.fail(function () {
alert("error");
})
.always(function () {
alert("complete");
});
Please try with the following.
app.controller('IModalCtrl', function ($scope,$rootScope, $http, $route, $routeParams, $location) {
$scope.will_call_this = function() {
//
};
$rootScope.$on('$routeChangeSuccess', function (event, next, current) {
$scope.will_call_this();
});
});
Related
I got some problem when I'm trying to use an Angular service in the controlleur of my application.
When I'm trying to use function of my service in my controlleur, my console throw me an error :/
var app = angular.module('app', ['ngRoute'])
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/login', {
controlleur: 'login',
templateUrl: 'modules/login/login.html'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.service('coreServices', [function () {
this.helloConsole = function () {
console.log("console services");
};
}]);
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, coreServices) {
var vm = this;
vm.helloConsole = coreServices.helloConsole;
vm.helloConsole();
}
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
I link you this fiddle to show you how I do: https://jsfiddle.net/h8yaxLap/2/
The error throwed is:
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
Well in your example angular will map $location to coreService in the injected parameters in the function. So I would go for
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, $location, coreServices)
Change service function to return object
app.service('coreServices', function () {
return {
helloConsole: function () {
console.log("console services");
}
};
});
You missed $location parameter for the controller
function LoginController($scope, $http, $rootScope,$location, coreServices)
Why $location.url( "/messages" ); is not working? is there any restriction about $location inside a factory in AngularJS? any idea what is going on?
If I'm doing something wrong can you please tell my how should I redirect to another url "/messages"? I can't reload the page using so $window is not an option.
Thanks
My factory:
(function () {
'use strict';
angular
.module('app.conversation')
.factory('conversationFactory', conversation);
conversation.$inject = ['$rootScope', '$q', 'authFactory', '$location'];
function conversation($rootScope, $q, authFactory, $location) {
var service = {
changeLocation: changeLocation
};
return service;
function changeLocation() {
$location.url( "/messages" ); // recarga MIERDA!!!!!
}
}
})();
Route works fine:
(function () {
'use strict';
angular
.module('app.messages')
.config(configFunction);
configFunction.$inject = ['$routeProvider'];
function configFunction($routeProvider) {
$routeProvider
.when('/messages', {
templateUrl: 'app/messages/messages.html',
controller: 'messagesController',
controllerAs: 'meC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
}).when('/compose/:to?', {
templateUrl: 'app/messages/compose.html',
controller: 'composeController',
controllerAs: 'mcC',
resolve: {
user: function ($q, $timeout, authFactory) {
return authFactory.isLoggedInPromise();
}
}
});
}
})();
use $location.path( "/messages" );
I did:
$location.path( "/messages" ); // and then
$rootScope.$apply()
$location.path doesn't change in a factory with AngularJS
I would like to pass article id from url to factory but I can't get the value from $routeChangeSuccess callback.
myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {
var article_id = $rootScope.$on('$routeChangeSuccess', function () {
return $routeParams.id;
});
getArticleById.get(article_id).then(function(data) {
$scope.articles = data;
});
});
myApp.factory('getArticleById', function($q, $http) {
return {
get: function(article_id) {
var deferred = $q.defer();
$http.get('/api/admin/article/edit/'+ article_id).success(function(result) {
deferred.resolve(result);
}).error(function(result) {
deferred.reject(result);
});
return deferred.promise;
}
}
});
$routeProvider
var myApp = angular.module('myApp',['ngRoute','ui.utils','ngSanitize','ui.tinymce'])
.config(function ($routeProvider, $locationProvider) {
//configure the routing rules here
$routeProvider.when('/admin/article/edit/:id', {
controller: 'editCtrl'
});
//routing DOESN'T work without html5Mode
$locationProvider.html5Mode(true);
}
);
Instead of creating a var named article_id in your controller, simply use the $routeParams.id to pass the value to factory.
getArticleById.get($routeParams.id).then(function(data) {
$scope.articles = data;
});
You can just update the articles in the $routeChangeSuccess callback.
myApp.controller('editCtrl', function($rootScope, $scope, getArticleById, $filter, $route, $routeParams) {
$rootScope.$on('$routeChangeSuccess', function () {
getArticleById.get($routeParams.id).then(function(data) {
$scope.articles = data;
});
});
});
This might cause problems when there is multiple route changes in quick successions. In which case you would need to do some more work.
I'm working on a Themeforest-Template,where the controllers looks like this:
(function () {
"use strict";
angular.module("app.tables", []).controller("articlesCtrl", ["$scope", "$http",
function ($scope, $http) {
$http.get('www/articles.php?method=fetchAll').success(function (data) {
$scope.articles = data;
console.log($scope.articles);
}).
error(function (data) {
// log error
})
}
])}.call(this))
Everywhere in the web I find guides and tutorials where the controllers looks like this:
app.factory('articlesFactory', function ($http, $resource) {
$http.get('www/articles.php?method=fetchAll').success(function (data) {
return $resource(data);
});
app.controller('articlesCtrl', function ($scope, articlesFactory) {
$scope.articles = articlesFactory.query();
})});
why does this not work for me ?
my app.js looks like this:
(function () {
'use strict';
angular.module('app', [
'ngRoute',
'ngAnimate',
'ui.bootstrap',
'easypiechart',
'textAngular',
'ui.tree',
'ngMap',
'ngTagsInput',
'app.controllers',
'app.directives',
'app.directives',
'app.localization',
'app.nav',
'app.ui.ctrls',
'app.ui.directives',
'app.ui.services',
'app.ui.map',
'app.form.validation',
'app.ui.form.ctrls',
'app.ui.form.directives',
'app.tables',
'app.task',
'app.chart.ctrls',
'app.chart.directives',
'app.page.ctrls',
'app.calls',
'app.avgLic'
]).config([
'$routeProvider', function ($routeProvider) {
var routes, setRoutes;
routes = [
"calls/calls",
"calls/archive",
"calls/statistics",
"calls/sms",
"contacts/contacts",
"configurator/configurator",
"configurator/offers",
"configurator/search",
"configurator/articles",
"configurator/orders",
"configurator/distributors",
"orders/new_orders",
"orders/archive",
"avg/active_lic",
"avg/new_lic"
];
setRoutes = function (route) {
var config, url;
url = '/' + route;
config = {
templateUrl: 'views/' + route + '.html'
};
$routeProvider.when(url, config);
return $routeProvider;
};
routes.forEach(function (route) {
return setRoutes(route);
});
return $routeProvider.when('/', {
redirectTo: '/calls/calls'
}).when('/404', {
templateUrl: 'views/pages/404.html'
}).otherwise({
redirectTo: '/404'
});
}
]);}).call(this);
I want to show url as "www.test.com/!#" for that i am using $locationProvider.hashPrefix("!") ; but it shows url as "www.test.com/#!" . i want "!" before hash not after hash.
Thanks
var app = angular.module('app', []);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(false);
$locationProvider.hashPrefix("!");
$routeProvider.when('/', {
templateUrl: "app.html",
controller: "AppCtrl"
}
)
.when('/Program', {
templateUrl: "detail1.html",
controller: "Redirect"
})
.when('/Program/123456/channel/78458585',
{
templateUrl: "details.html",
controller: "Detail"
});
});
app.controller("AppCtrl", function ($scope) {
});
app.controller("Detail", function ($scope, $location) {
});
app.controller("Redirect", function ($scope, $location) {
$location.path("/Program/123456/channel/78458585")
});
If you want a ! in the URL before the fragment identifier begins, then you need to put it in the URL to start with and not try to do it with Angular.
http://www.example.com/#foo and http://www.example.com/#!foo are different parts of the same page.
But http://www.example.com/#foo and http://www.example.com/!#foo are different pages altogether.