angularjs - access url parameters in controller - javascript

I am trying to access url params in my controller:
I found this example, but I get an error that I think is related to loading the relevant modules.
app.controller('WidgetCtrl', ['$scope', '$routeParams', function ($scope, $routeParams, $http) {
var param1 = $routeParams.param1;
var param2 = $routeParams.param2;
var vm = $scope;
vm.data = "test";
}]);
Error:
Uncaught Error: [$injector:modulerr]
In my html I have:
<script src=".../angular-1.2.21/angular.min.js"></script>
<script src=".../angular-1.2.21/angular-route.min.js"></script>
What is the proper wat to access the url params and use them in the controller? which modules I need to load?

From the looks of it, you're not injecting $http, so it should be:
app.controller('WidgetCtrl', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
That should get rid of that error.

Related

Dynamic loading Angular Controller

I am trying to load controllers dynamically using ocLazyLoad :
$ocLazyLoad.load('./ctrls/login.js');
But am getting this error saying:
The controller with the name 'loginCtrl' is not registered.
angular.module('optimusApp')
.controller('loginCtrl', function ($scope, $rootScope, $location, $http) {});
app.js
angular.module("optimusApp", ['ngRoute', 'oc.lazyLoad']);
angular.module('optimusApp')
.controller('globalCtrl', function ($rootScope, $location, $http, $routeParams, $ocLazyLoad) {
$ocLazyLoad.load('./ctrls/login.js');
});
I made it work by using ng-if
app.js
var optimusApp = angular.module("optimusApp", ["ngRoute", "oc.lazyLoad"])
.controller("globalCtrl", function ($rootScope, $location, $http, $routeParams, $ocLazyLoad) {
$ocLazyLoad.load("./js/app/login.js").then(function() {
console.log("loginCtrl loaded");
$rootScope.loginActive = true;
}, function(e) {
console.log("error");
});
});
login.js
optimusApp.controller('loginCtrl', function ($scope, $rootScope, $location, $http) {
});
HTML
<div ng-if="loginActive" ng-controller="loginCtrl">
</div>
Basically you will get the "registration error" if your ng-controller is in the page before you have the JS loaded.
So the ng-if is a solution, or I see you have ngRoute. So you could set ocLazyLoad to load the controller when entering a specific state.

AngularJS TypeError is not a function

I have the following code in my service:
testApp.service('detailsService',['databaseService', 'loggedService', '$http', function(databaseService, loggedService, $http){
var details;
this.getDetails = function(name){
return $http({
method : "GET",
url : name
}).then(function(response) {
details= response.data;
console.log(response.data);
return response.data;
});
};
}]);
What i want to do is call this function in my controller when the page(view) is loaded.
testApp.controller('testController', ['$scope', '$location', 'databaseService','detailsService', '$routeParams', function($scope, $location, databaseService, $routeParams, detailsService){
$scope.details;
var selectedDetails = function(name){
detailsService.getDetails(name).then(function(data){
$scope.details= data;
});
};
selectedDetails(name);
}]);
I keep getting the error detailsService.getDetails is not a function.
I'm using the same function from the detailsService in another controller without any problems.
Does anybody know why i keep getting this error?
The error is expected as you are not injecting dependencies properly, You need to use the correct sequence.
testApp.controller('testController', ['$scope',
'$location',
'databaseService',
'detailsService',
'$routeParams',
function($scope, $location, databaseService, detailsService, $routeParams ){
instead of
testApp.controller('testController', ['$scope',
'$location',
'databaseService',
'detailsService',
'$routeParams',
function($scope, $location, databaseService, $routeParams, detailsService){
Note Both the string part and the function arguments need to match up 1:1.
remove the promise in the service.Just return the request. since you are catching the promise from the controller no need to use it in the service
testApp.service('detailsService', ['databaseService', 'loggedService', '$http', function(databaseService, loggedService, $http) {
var details;
this.getDetails = function(name) {
return $http({
method: "GET",
url: name
})
};
}]);
Also make sure the sequence is correct order when you are injecting services.
change this
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, $routeParams, detailsService )
to this
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, detailsService , $routeParams)
controller
testApp.controller('testController', ['$scope', '$location', 'databaseService', 'detailsService', '$routeParams', function($scope, $location, databaseService, detailsService , $routeParams) {
$scope.details;
var selectedDetails = function(name) {
detailsService.getDetails(name).then(function(data) {
$scope.details = data;
});
};
selectedDetails(name);
}]);
I got this error because I had added a callback method to a component, but the callback was not used by all the pages where that component was used:
<component [myCallbackFn]="fnNameToBindToFn">
component.ts:
public onClick() {
// some code
this.myCallbackFn();
}
Each time it was not used I got this error which was effectively a NullPointerException (from Java). So in the other uses of <component> in my website I had to add a check in the component before the callback to say:
if (undefined !== this.myCallbackFn) this.myCallbackFn();

Angularjs factory inject error

I'm using angularJS and when I'm injecting a Factory I get error:
app.js :
angular.module('myapp', [])
myfactory.js :
angular.module('myapp', [])
.factory('httpService', function($http, $timeout) {
});
Controller: test.js :
angular.module('myapp', [])
.controller('test', function($scope, $timeout, $sce, $http, httpService) {
$scope.submit = function() {
}
});
When I add httpService I get error. Everything seems to be right, I even use this factory in all projects. Error:
angular.min.js:92 Error: [$injector:unpr] http://errors.angularjs.org/1.2.25/$injector/unpr?p0=httpServiceProvider%20%3C-%20httpService
at Error (native)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:6:450
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:36:202
at Object.c [as get] (http://localhost:81/chah/assets/js/angularjs/angular.min.js:34:305)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:36:270
at c (http://localhost:81/chah/assets/js/angularjs/angular.min.js:34:305)
at d (http://localhost:81/chah/assets/js/angularjs/angular.min.js:35:6)
at Object.instantiate (http://localhost:81/chah/assets/js/angularjs/angular.min.js:35:165)
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:67:419
at http://localhost:81/chah/assets/js/angularjs/angular.min.js:54:25
Check the link in your error (https://docs.angularjs.org/error/$injector/unpr?p0=httpServiceProvider%20%3C-%20httpService):
You create module multiple times:
angular.module('myapp', [])
You should do it once. Then use without []
angular.module('myapp').factory ...
angular.module('myapp').controller ...
The reason for the error is because in the creation of the httpService and the controller you have used the setter i.e. angular.module('myapp', []) syntax for the module and not the getter syntax. angular.module('myapp').
Angular requires us to define a module only once, thus the subsequent redefining causes the error.
So in app.js, define the module:
angular.module('myapp', []) ;
In myfactory.js use the getter Syntax by removing the , []:
angular.module('myapp')
.factory('httpService', function($http, $timeout) {
});
And in test.js:
angular.module('myapp')
.controller('test', function($scope, $timeout, $sce, $http, httpService) {
$scope.submit = function() {
}
});
Here is a link to the docs
yes,
what you are doing is re-creating your app
what you need to do is define it once and continue using that instance
var app = angular.module('myapp', []);
app.factory('httpService', function($http, $timeout) {
});
app.controller('test', function($scope, $timeout, $sce, $http, httpService) {
$scope.submit = function() {
}
});
or if you want to retrieve your app the syntax is angular.module('myapp')
this returns 'myapp', but adding [], tells angular to create an app and not fetch it
Code should look like below:
angular.module('myapp', [])
.factory('httpService', function($http, $timeout) {
});
.controller('test', function($scope, $timeout, $sce, $http, httpService) {
$scope.submit = function() {
}
});

angular.js routing and stateparams

I'm trying to modify standard user module of meanjs. I added a simple route:
state('users', {
url: '/users/:username',
templateUrl: 'modules/users/views/view-profile.client.view.html'
});
And in my view:
data-ng-controller="ViewProfileController" data-ng-init="findUser()"
I also injected $stateParams to my controller. So in my ViewProfileController - findUser function, when I write this:
console.log($stateParams.username)
I expect to get username parameter. But it returns undefined.
When I set the route this way,
state('users', {
url: '/users/:username',
template: function ($stateParams){
return $stateParams.username;
}
});
it returns username. I don't know what is wrong or missing. Any ideas?
edit: this was my full controller code
'use strict';
angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
function($scope, $http, $location, Users, Authentication, $stateParams) {
$scope.user = Authentication.user;
$scope.findUser = function () {
console.log($stateParams);
...
};
}
]);
Your dependencies don't match up - the list of dependencies need to match the parameters in the controller function in the same order:
'use strict';
angular.module('users')
.controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
function($scope, $http, $stateParams, $location, Users, Authentication) {
$scope.user = Authentication.user;
$scope.findUser = function () {
console.log($stateParams);
};
}
]);
I should use controller instead of template.
Replace into you code the template: to the follow snippet:
controller: function($stateParams){
console.log('username: '+$stateParams.username);
}
You can see a complete example of this feature here

query() with Angular $resources, "Undefined is not a function"

So I am experimenting with Angular. I created the following module.
var archiveModule = angular.module('archiveModule', ['ngResource']);
archiveModule.factory('Archive', ['$resource',
function($resource) {
return $resource('/data/archive/:doc.json', {}, {
query: { method:'GET', params:{ doc: undefined }, isArray:true }
});
}]);
archiveModule.controller('ArchiveControl', ['$scope', '$http', 'Archive',
function ($scope, Archive) {
$scope.items = Archive.query();
$scope.orderProp = 'name';
}]);
My template everything happens within:
<div class="container" ng-app="archiveModule">
<div ng-controller="ArchiveControl">
I include the angular scripts at the bottom of my page:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-resource.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular-route.js"></script>
And Chrome reports TypeError: undefined is not a function, and it goes back to the line $scope.items = Archive.query();.
According to http://docs.angularjs.org/api/ngResource.$resource, query is part of $resource and I modeled my resource off http://docs.angularjs.org/tutorial/step_11 I'm not sure what's going wrong here.
Your parameters don't line up with the dependencies that are declared. It's injecting $http into Archive...
archiveModule.controller('ArchiveControl', ['$scope', '$http', 'Archive',
function ($scope, Archive) {
Remove '$http' and it should work...
archiveModule.controller('ArchiveControl', ['$scope', 'Archive',
function ($scope, Archive) {
$scope.items = Archive.query();
$scope.orderProp = 'name';
}]);

Categories

Resources