$location.path() not working in AngularJS - javascript

I have been trying to redirect my application to the following link using
$location.path('/enterprise/update/' + enterprise.id);
The current url when I click the button is http://localhost:8080/#/enterprise/view
and I would like it to be changed to http://localhost:8080/#/enterprise/update/0
(The 0 here represents the id)
The edit function is the one which is called when I click on the button to redirect.
Relevant code:
EnterpriseCtrl.js
app.controller('EnterpriseCtrl', ['$scope', 'Enterprise', '$location','$http','$route','$routeParams','$resource', function($scope, Enterprise, $http, $route, $location, $rootScope) {
$scope.enterprises = Enterprise.list({}, function (response) {
return response;
});
$scope.add = function(){
Enterprise.save($scope.enterprise,function (){});
$scope.enterprise = null;
};
$scope.delete = function(enterprise, index){
alert("Do you really want to delete an Enterprise at index " + (index+1) + "?");
//book.$remove();
Enterprise.remove(enterprise);
$scope.enterprises.splice(index, 1);
};
$scope.edit = function(enterprise){
console.log(enterprise.id);
console.log(location);
console.log($location);
$location.path('/enterprise/update/' + enterprise.id);
};
// $scope.enterprise = Enterprise.get({id: $route.current.params.id});
$scope.update = function(){
Enterprise.update($route.current.params.id);
$location.path($rootScope.history.view);
};
}]);
app.js
var app = angular.module('mpsApp', ['ngRoute','ngResource']);
app.config(['$routeProvider','$locationProvider',
function ($routeProvider,$locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html'
}).
when('/enterprise/view', {
controller: 'EnterpriseCtrl',
templateUrl: 'showEnterprise.html'
}).
when('/enterprise/add', {
controller: 'EnterpriseCtrl',
templateUrl: 'addEnterprise.html'
}).
when('/enterprise/update/:id', {
controller: 'EnterpriseCtrl',
templateUrl: 'updateEnterprise.html'
}).
otherwise({
redirectTo: '/'
});
}
]);
The error that I get is
TypeError: $location.path is not a function
at Scope.$scope.edit (EnterpriseCtrl.js:29)
at $parseFunctionCall (angular.js:12330)
at callback (angular.js:22940)
at Scope.$eval (angular.js:14381)
at Scope.$apply (angular.js:14480)
at HTMLButtonElement.<anonymous> (angular.js:22945)
at HTMLButtonElement.eventHandler (angular.js:3009)

Your dependency injection array/parameters are out of order. Should be:
[ '$scope', 'Enterprise', '$location', '$http', '$route', '$routeParams', '$resource',
function($scope, Enterprise, $location, $http, $route, $routeParams, $resource) {
Note, how each single array element service corresponds to the parameters in the function.

Related

AngularJS - how to get the parameter from URL

I'm trying to pass the parameters to the AngularJS controller.
AngularJs Routes
$routeProvider.when('/post-ads/', {
templateUrl: "ui/view/post-ads.php",
controller: "adPostController",
controllerAs: 'vm'
})
$routeProvider.when('/post-ads/:category/:subcategory', {
templateUrl: "ui/view/ad-details.php",
controller: "adPostController",
controllerAs: 'vm'
})
AdPostController
adPostController.$inject = ['ApiService', '$scope'];
function adPostController(ApiService, $scope, $routeParams) {
console.log("im here");
console.log($routeParams.category, $routeParams.subcategory);
}
HTML a href
<a href="#/post-ads/automobile/car>click</a>
Error
TypeError: Cannot read property 'category' of undefined
I guess your have to change:
adPostController.$inject = ['ApiService', '$scope'];
function adPostController(ApiService, $scope, $routeParams) {
console.log("im here");
console.log($routeParams.category, $routeParams.subcategory);
}
To:
adPostController.$inject = ['ApiService', '$scope', '$srouteParams'];
function adPostController(ApiService, $scope, $routeParams) {
console.log("im here");
console.log($routeParams.category, $routeParams.subcategory);
}
Change to this:
adPostController.$inject = ['ApiService', '$scope', '$routeParams'];

$routeParams Empty on $locationChangeSuccess

I configure my app in the following run block. Basically I want to preform an action that requires me to know the $routeParams every $locationChangeSuccess.
However $routeParams is empty at this point! Are there any work rounds? What's going on?
app.run(['$routeParams', function ($routeParams) {
$rootScope.$on("$locationChangeSuccess", function () {
console.log($routeParams);
});
}]);
UPDATE
function configureApp(app, user) {
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/rentroll', {
templateUrl: 'rent-roll/rent-roll.html',
controller: 'pwRentRollCtrl'
}).
when('/bill', {
templateUrl: 'bill/bill/bill.html',
controller: 'pwBillCtrl'
}).
when('/fileroom', {
templateUrl: 'file-room/file-room/file-room.html',
controller: 'pwFileRoomCtrl'
}).
when('/estate-creator', {
templateUrl: 'estate/creator.html'
}).
when('/estate-manager', {
templateUrl: 'estate/manager.html',
controller: 'pwEstateManagerCtrl'
}).
when('/welcomepage', {
templateURL: 'welcome-page/welcome-page.html',
controller: 'welcomePageCtrl'
}).
otherwise({
redirectTo: '/welcomepage'
});
}]);
app.run(['$rootScope', '$routeParams', 'pwCurrentEstate','pwToolbar', function ($rootScope, $routeParams, pwCurrentEstate, pwToolbar) {
$rootScope.user = user;
$rootScope.$on("$locationChangeSuccess", function () {
pwToolbar.reset();
console.log($routeParams);
});
}]);
}
Accessing URL:
http://localhost:8080/landlord/#/rentroll?landlord-account-id=ahlwcm9wZXJ0eS1tYW5hZ2VtZW50LXN1aXRlchwLEg9MYW5kbG9yZEFjY291bnQYgICAgICAgAoM&billing-month=2014-06
this worked for me, inside your run callback:
.run(function($rootScope, $routeParams, $location) {
$rootScope.$on("$locationChangeSuccess", function() {
var params = $location.search();
console.log(params);
console.log('landlord-account-id:', params['landlord-account-id']);
console.log('billing-month', params['billing-month']);
});
})
By accessing /rentroll you will get empty $routeParams because your $routeProvider
configuration for that path is not expecting any variable on URL.
$routeParams is used for getting variable value of your URL. For example :
$routeProvider
.when('/rentroll/:variable', {...});
and access it on /rentroll/something will give you $routeParams as below :
$routeParams.variable == 'something';
https://docs.angularjs.org/api/ngRoute/service/$routeParams
Explains a bit about when the $routeParams are available and why.
To solution here might be to use $route.current.params

Undefined is not a function error when using factory method in angularJS

I'm having problems finding the solution to TypeError: undefined is not a function in my code.
I have the following app.js:
var app = angular.module('test', ['ngRoute', 'test.services', 'test.directives', 'test.controllers']);
app.config(function ($routeProvider, $httpProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/q/:q', {
templateUrl: '/templates/productlist.html',
controller: 'ProductCtrl'
}).
otherwise({
redirectTo: '/q'
});
});
Then I have a controller
var controllers = angular.module('test.controllers', []);
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
function ($scope, ProductFactory, $routeParams) {
$scope.query = $routeParams.q;
$scope.products = ProductFactory.query({query: $scope.query});
}]);
And a factory
var services = angular.module('test.services', ['ngResource']);
var baseUrl = 'http://localhost\\:8080';
services.factory('ProductFactory', function ($resource) {
return $resource(baseUrl + '/test/smart/:query', {}, {
query: { method: 'GET', isArray: true }
})
});
This code results on load in the above mentioned TypeError on the line $scope.products = ProductFactory.query({query: $scope.query}); in my controller.
Further, when debugging my code I see that $routeParams.q is null or undefined.
What I want is that in my controller the $scope.products variable becomes an array with the result of the query.
What am I doing wrong?
Please try with correct function arguments,
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
function ($scope /*ProductFactory*/, $routeParams, ProductFactory) {
$scope.query = $routeParams.q;
$scope.products = ProductFactory.query({query: $scope.query});
}]);

Using Angular services to hold commonly required data

I am currently writing my first application in Angular and have been very much enjoying all the framework has to offer so far. Like most newbies I set off building everything into a main controller, copying the tutorials. I am now seeing the error of my ways and refactoring.
My question is about services holding data that is commonly required among controllers.
I've now taken the data out of the 'main controller' and placed it into a service that I have injected into both controllers requiring access. Now though neither controller sees the functionality I've defined in the new service:
varianceService is not defined
Being new to this approach i welcome all and any help, aswell as help with my current problem, any comments on the best way to apply this approach would also be highly appreciated.
Thanks in advance.
Here is an example of the code:
var app = angular.module(
'VarianceAnalysis', ['ngRoute', 'ngAnimate', 'mgcrea.ngStrap', 'mgcrea.ngStrap.tooltip', 'mgcrea.ngStrap.helpers.dateParser', 'SharedServices']
)
.service('varianceService', function () {
var variances = {};
return {
redirect: function (path) {
$location.path(path);
},
getHttpVariances: function (month1, month2) {
var url = "/Home/GetVariances?month_1=";
url += month1;
url += "&month_2="
url += month2;
url += "&forwardBilling=true"
$http.get(url).success(function (data) {
variances = data;
return data;
});
return {};
},
getVariances: function () {
return variances;
}
};
})
.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/MainPage', {
templateUrl: 'mainpage.html',
controller: 'MainPageCtrl'
}).
when('/Variance/:type', {
templateUrl: 'variance.html',
controller: 'VarianceCtrl'
}).
otherwise({
redirectTo: '/MainPage'
});
}])
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', 'varianceService', function ($scope, $http, $location) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
The problems lies in the bracket notation of injecting services in your function..
What you inject in the bracket notation must also be present in the function definition..
e.g.
controller('MyCtrl', ['$scope', '$http', 'varianceService', function($scope, $http, varianceService) {
}]);
so in relation to your code above.. it should be like this..
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])
.controller('MainPageCtrl', ['$scope', '$http', '$location', 'varianceService', function ($scope, $http, $location, varianceService) {
$scope.go = function (month1, month 2) {
$scope.variances = varianceService.getHttpVariances(month1, month2);
}]);
just as how you have ordered the injected services in your bracket notation, it must also pertain the same order in your function definition.
Change this
.controller('VarianceCtrl', ['$scope', 'varianceService', function ($scope, $http, $location, $routeParams) {
$scope.variance_type = varianceService.getVariances();
}])
to
.controller('VarianceCtrl', ['$scope', '$http', '$location', '$routeParams', 'varianceService', function ($scope, $http, $location, $routeParams, varianceService) {
$scope.variance_type = varianceService.getVariances();
}])

How can I send URLstring as get params in AngularJS?

I want send a "URL" as get params in AngularJS.
===
success:
example.com/purchase/loremipsum
failed(redirect to otherwise):
example.com/purchase/http%3A%2F%2Fwww.google.com
==
javascript
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/gallery', {
templateUrl: 'partials/gallery.html',
controller: 'galleryCtrl'
}).
when('/purchase/:url', {
templateUrl: 'partials/purchase.html',
controller: 'PurchaseCtrl'
});
}]);
app.controller('GalleryCtrl',function ($scope, $http, $rootScope, $routeParams, $modal, $log, $location){
$http.get(url).
success(function(data){
$scope.itemUrl = encodeURIComponent(data.url);
});
});
app.controller('PurchaseCtrl',function ($scope, $http, $rootScope, $routeParams, $modal, $log, $location){
$scope.url = $routeParams.url;
alert($scope.log);
});
gallery.html
<a ng-href="#/purchase/{{itemUrl}}">BUY</a></div>
%2F will be converted into a '/'
That means angular will try to find match for example.com/purchase/http://www.google.com, which doesn't match your pattern '/purchase/:url'

Categories