How to read url query parameters with AngularJS? - angularjs

I'd like to get the value of specific url parameters using AngularJS. I then want to assign a specific value to a specific textbox.
An example URL might look like:
http://example.com/?param1=value1
I've seen examples about $location, routing and services. I don't want to do any of that. I just need the value of param1. Any ideas how that can be done?
Here's a corresponding jsfiddle.net with several attempts: http://jsfiddle.net/PT5BG/211/

Using $location is the angular way
$location.search().param1; should give it if html5mode=true
Otherwise you have to use pure javascript. Check this.
How can I get a specific parameter from location.search?

If you are using ngRoute, look for routeParams
If you using ui-Router, look for stateParams
JS way:
var key = 'param1';
var value = window.location.search.substring(window.location.search.indexOf(key)+key.length+1);

Try this.You need to route concept in angular js
<!DOCTYPE html>
<html lang="en">
<head>
<title>AngularJS Routes example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>
<body ng-app="sampleApp">
Route 1 + param<br/>
Route 2 + param<br/>
{{param}}
<div ng-view></div>
<script>
var module = angular.module("sampleApp", ['ngRoute']);
module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1/:param', {
templateUrl: 'your_url1',
controller: 'RouteController'
}).
when('/route2/:param', {
templateUrl: 'your_url2',
controller: 'RouteController'
}).
otherwise({
redirectTo: '/'
});
}]);
module.controller("RouteController", function($scope, $routeParams) {
$scope.param = $routeParams.param;
alert($scope.param);
})
</script>
</body>
</html>
$routeParams allows you dto the value of parameter

Related

Angular js controller not working after modularizing app

I'm new to angularjs and followed the tutorial here from w3schools to create my first simple Angularjs app and it worked fine. After going through the official angularjs tutorial I decided to modularize my app but now its not working. Currently I m getting the error
"The controller with the name 'redController' is not registered."
I want to display a message in component 'red' using its controller. I tried altering many parts of the code only to get new errors and it seems I have messed up modularizing :|
I'm using v1.6.9
Here is my directory structure
app/
scripts/
angular.min.js
angular-route.js
blue/
blue.template.html
red/
red.template.html
red.module.js
red.component.js
app.config.js
app.module.js
index.html
and source files :
app.config.js
angular
.module("myApp", [ 'red','ngRoute' ])
.config(function($routeProvider) {
$routeProvider
.when("/red", {
templateUrl : "red/red.template.html",
controller: "redController"
})
.when("/blue", {
templateUrl : "blue/blue.template.html"
});
});
app.module.js
angular.module('myApp', [
'red',
'ngRoute'
]);
index.html
<!DOCTYPE html>
<html>
<script src="scripts/angular.min.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="app.module.js"></script>
<script src="app.config.js"></script>
<script src="red/red.module.js"></script>
<script src="red/red.component.js"></script>
<body ng-app="myApp">
Red
Blue
<div ng-view></div>
<p>Click on the links to navigate "</p>
</body>
</html>
red.template.html
<h1>red</h1>
<p>{{msg}}</p>hell
red.module.js
angular.module('red', [ 'ngRoute' ]);
red.component.js
angular.module('red').component('red',{
templateUrl: 'red/red.template.html',
controller: function redController() {
this.msg = "this is red";
console.log("Hi");
}
});
You are delcaring the module again and again in each .js files, declare only in one .js file and use it in rest of the fields.
change your red.module.js as,
angular.module('red', []);
your app.config.js should be as,
angular
.module("myApp")
.config(function($routeProvider) {
$routeProvider
.when("/red", {
templateUrl : "red/red.template.html",
controller: "redController"
})
.when("/blue", {
templateUrl : "blue/blue.template.html"
});
});
and change the order as follows,
<script src="red/red.module.js"></script>
<script src="app.module.js"></script>
<script src="app.config.js"></script>
<script src="red/red.component.js"></script>
Change red.component.js as follows
angular.module('red')
.component('red',{
templateUrl:
'red/red.template.html',
})
.controller("redController",function($scope)
{
$scope.msg ="This is red";
});
First of all, as #Sajeetharan you're defining the myApp module twice. Inside your app.config.js and also in app.module.js. If you use angular.module with 2 parameters angular.module('app', []) you're setting the module, if you use angular.module('app') it'll work as a getter. So, in your app.config.js you should use the getter to configure your app.
Once you did that, you can configure your route to something like this:
angular.module('myApp').config(function($routeProvider){
$routeProvider.when('/red', { template: '<red></red>'});
})
I would use this approach since you defined the component in another module.
If you still want to use the approach you've implemented to set both the templateUrl and controller in the $routeProvider, you'll have to change your red component declaration to something like this:
angular.module('red')
.component('red', { templateUrl: 'red/red.template.html'})
.controller('redController', function(){
this.msg = 'This is red.';
});
I'vent tested this second approach as for me the first makes more sense.

Angular JS $location.path() getter not updating

I want to use the $location.path() method to return the URL path so I can write some conditional statements in an ng-hide directive. I created the following in my controller:
$scope.pathLocation = $location.path();
I then inserted {{pathLocation}} in my html just to make sure it was returning the correct path, which it is. The problem comes when I load a different view. The pathLocation doesn't update. If I manually refresh my browser on the new page view, it does. `
Here is an abbreviated version of my code:
Controller:
(function(){
var amApp = angular.module('amApp', ['ngRoute', 'ngCookies','ngAnimate' ]);
amApp.controller('WelcomeController', ['$scope', '$location', function WelcomeController($scope, $location) {
$scope.pathLocation = $location.path();
}]);
})();
Here is the HTML:
<html lang="en" ng-app="amApp">
<body ng-controller="WelcomeController as welcome">
<nav>menu's here to different views in SPA</nav>
{{pathLocation}}
<div ng-view></div>
</body>
As mentioned in my comment, nothing in your code updates your pathLocation property. Try adding this
$scope.$on('$locationChangeSuccess', function() {
$scope.pathLocation = $location.path();
});
Publish the function on scope:
amApp.controller('WelcomeController', ['$scope', '$location', function WelcomeController($scope, $location) {
//$scope.pathLocation = $location.path();
$scope.locationPathFn = $location.path;
}]);
Then execute the function in the HTML:
<html lang="en" ng-app="amApp">
<body ng-controller="WelcomeController as welcome">
<nav>menu's here to different views in SPA</nav>
{{locationPathFn()}}
<div ng-view></div>
</body>
Then on every digest cycle the $location.path() function will be checked and the view kept up to date.

$watch for location.hash changes

In my angular app I am trying to change the location to "#home" when the user enters an invalid route.
Here's a short but complete app demonstrating what I did.
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script>
angular.module('app', [])
.controller('ctrl', function($scope, $location, $window) {
$scope.$watch (function() { return $location.url() }, function(url) {
if (url == '')
$window.location = '#home'
})
})
</script>
</head>
<body ng-app="app" ng-controller="ctrl"></body>
</html>
But when I do this I get an infdig error when the page loads. I don't know whats wrong.
Edit:
I don't want to use routing libraries like "ui-router". so answers like this one that uses the "angular-route" library are not helpful.
You can specify that in app.config block using $routeProvider.
app.config(function ($routeProvider) {
$routeProvider
.when('/home', {
template: 'home.html',
controller: 'homeController'
})
.otherwise('/home');
});
.otherwise method will redirect the application to /home, if user tries to access any invalid path which is not specified in config.
Update:
And, If you don't want to use angular routing library you can use native javascript event hashchange on window to listen for hash change events. and redirect accordingly.
see the below example.
function locationHashChanged() {
if (location.hash !== "#/home") {
console.log('hash is other then #home. will redirect to #home');
console.log('Full path before', document.URL);
window.location.hash = '#/home';
console.log('Full path after', document.URL);
}
}
window.addEventListener('load', locationHashChanged);
window.addEventListener('hashchange', locationHashChanged);
Home
<br/>
Some-Site
<br/>
Other

angular and ui-router example is not working

Hello I'm trying a simple application with Angular and UI-Router...
But for some reason, it's not working at all.
In chrome, there is no error in the console, but there is even no output at all
Maybe some one has some clue on what's happening... I definitely have no idea.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="/Scripts/angular.min.js"></script>
<script src="/Scripts/angular-ui-router.js"></script>
</head>
<body>
<div>
Route 1
<div ui-view="viewSidebar"></div>
<div ui-view="viewContent"></div>
</div>
<script>
var app = angular.module('app', ['ui.router']);
app.config(
['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/media/list');
$stateProvider.state('mediaList', {
views: {
url: "/media/list",
'viewSidebar': {
template: '<p>SideBar</p>',
controller: 'SidebarControllerView'
},
'viewContent': {
template: '<p>Thumb view</p>',
controller: 'MediaControllerView'
}
}
});
}]);
app.controller('MediaControllerView', ['$scope', MediaControllerView]);
app.controller('SidebarControllerView', ['$scope', SidebarControllerView]);
function MediaControllerView($scope) {
$scope.model = 1;
};
function SidebarControllerView($scope) {
$scope.model = 1;
};
</script>
</body>
</html>
There is a working plunker
One important wrong setting is the URL. It does not belong to the view, but to the state:
...
$stateProvider.state('mediaList', {
// url belongs to the state
url: "/media/list",
views: {
// url does not belong to the views
// url: "/media/list",
'viewSidebar': {
template: '<p>SideBar</p>',
controller: 'SidebarControllerView'
},
'viewContent': {
template: '<p>Thumb view</p>',
controller: 'MediaControllerView'
}
}
});
...
Check it here
And also, as DTing spotted we have to provide ng-app:
<html ng-app="app" ng-strict-di>
...
NOTE: ng-strict-di is not a must but... it is a must - to avoid later issues...
if this attribute is present on the app element, the injector will be created in "strict-di" mode. This means that the application will fail to invoke functions which do not use explicit function annotation (and are thus unsuitable for minification), as described in the Dependency Injection guide, and useful debugging info will assist in tracking down the root of these bugs.

Update ng-class on HTML tag when routing

I'm writing a Chrome extension using AngularJS. The UI is served via a browser action popup and as the content changes I sometimes need to change the size of the popup. The only way I've been able to do this is to change the CSS sizing attributes on the HTML and BODY tags via conditional updates of the class, i.e.
<!DOCTYPE html>
<html lang="en" ng-app="oApp" ng-controller="QuestionsCtrl" ng-class="{true:'expand'}[doExpand]">
<head>
...
</head>
<body ng-class="{true:'expand'}[doExpand]">
...
I have an ng-click on a control that sets 'doExpand' and this works nicely. However, I'm updating the app now to use routing to display multiple views. In doing that I'm removing the inline controller declaration...
<!DOCTYPE html>
<html lang="en" ng-app="oApp" ng-class="{true:'expand'}[doExpand]">
...
... and defining it in the routing config:
var oApp = angular.module('oApp', ['ngRoute', 'oControllers']);
oApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: '/partials/login.html',
controller: 'LoginCtrl'
}).
when('/board', {
templateUrl: 'partials/board.html',
controller: 'QuestionsCtrl'
}).
when('/board/:questionId', {
templateUrl: 'partials/question-detail.html',
controller: 'QuestionDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
}
]);
The routing is working but the problem is that the HTML tag is now outside the scope of the controller since that's now on the views themselves. I can stick the BODY tag in the views I suppose, but can't do the same for the HTML tag since the JS includes need to be in the head, etc. (and other reasons)
Can someone offer me advice on how to handle this scenario? Thank you!

Resources