AngularJS Controller depending on URL parameter - javascript

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.
I start to learn AngularJS and I have a very simple question :
Depending on ID contained in URL, I would like to display different BD record.
...
<div ng-app=MyApp>
<div ng-controller="MyCtrl">
{{ record }}
</div>
</div>
...
My Javascript file :
var MyApp = angular.module("MyApp",[]);
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/get/:productId', {
controller: 'MyCtrl'
});
}])
MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
function($scope,$routeParams,$http) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
}])
I tried to use $routeProvider and $routeParams without success.
Thank you in advance,
Bill

you need 2 things , the $routeParams injected in your controller and create a valid route with the get method
MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
function($scope,$http,$routeParams) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
};

Related

Angular Js linking a controller to a route doesn' work

I watching an Angular course on codeschool and it say that there are two way to link a controller to a route
The first one is declaring the controller inside the route like this:
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller: function(){.....}
})
the second way is to create a new file and then, over there, declare all the methods associate to that controller. After this have been done, we have to associate the controller to the route, like this.
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
This controller, I've made, import some data using an ajax call from a json file but it doesn't work well. I have to use this controller inside an HTML file
this is the controller
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('notes.json').success(function(data){
controller.notes = data;
})
}]);
This is the HTML code
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
the html should import all note stored inside the controller.notes array and display all it but it seems like the html doesn't recognize the controller and does't import anything.
The code works just if I declare inside the HTMl the controller I have to use like this:
<div ng-controller="NotesIndexController as indexController">
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
My question is. If I declare the controller inside my route why I should declare it also in my HTML?
Ok thanks everybody, I figured out what was the problem. This is the complete route.js file
angular.module('NotesApp',["ngRoute"])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:'templates/pages/notes/index.html',
controller:'NotesIndexController', // I have to declare the controller inside the template to make it work
controllerAs:'indexController'
})
.when('/users',{
templateUrl: 'templates/pages/users/index.html'
})
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
.when('/notes/:id', {
templateUrl:'templates/pages/notes/show.html',
controller:'NoteShowController',
controllerAs:'showController'
})
.otherwise({redirectTo:'/'});
}]);
The problem was the line:
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
instead, to load my controller should have been
.when('/',{
redirectTo: '/notes'
})
Please find this working plunk with your code
angular.module('NotesApp', ["ngRoute"])
.config(function($routeProvider){
$routeProvider.when('/', {
templateUrl:'main.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
})
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('data.json').success(function(data){
console.log(data)
controller.notes = data;
})
}]);

Angular - Controller as vm

Trying to get into the habit of using the controller as syntax, but seem to be missing something when trying out a simple example.
When trying to set a property like vm.name = 'John' it does not show up in my view when using {{vm.name}}.
Code is like so
controller
(function() {
'use strict';
angular
.module('myApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['dataService'];
function HomeController(dataService) {
var vm = this;
vm.data = {};
vm.name = 'Richard';
}
routes
'use strict';
angular
.module('myApp')
.config(function($routeProvider) {
$routeProvider.when(
'/view1',
{
templateUrl: 'partials/partial1.html',
controller: 'HomeController',
controllerAs: 'vm'
});
$routeProvider.when(
'/view2',
{
templateUrl: 'partials/partial2.html'
});
$routeProvider.otherwise(
{
redirectTo: '/view1'
});
});
view
<p>View 1</p>
<h1>Hello {{ vm.name }}</h1>
Not sure if you are using angular version more than 1.3, here is the working Plunker
Your HomeController should be changed like this,
app.controller("HomeController", function(){
this.name="Richard";
});
Use $scope. I think it will work. Write your code:
function HomeController(dataService) {
var vm = this;
vm.data = {};
vm.name = 'Richard';}
using $scope, try this one:
function HomeController($scope, dataService) {
$scope.data = {};
$scope.name = 'Richard';}
view
<p>View 1</p>
<h1>Hello {{name}}</h1>
Please read this article too!!!
You need to declare variables on the $scope object to achieve two way bindings. Otherwise its just a regular javascript variables. The scope is like a glue between your view and controller in angularjs.Read Here.
The only thing I can see as an issue is that you dont have ngRoute module included...
var app = angular.module('plunker', [
'ngRoute'
]);
or your dataservice isnt included as a script which is making the injection fail. Based off the information you have included I created a working plunkr for you using the view-model concept instead of $scope.
Heres angulars best practices which has some very useful information and examples on using the view-model concept, accompanied by a lot of other information Angular Guide

AngularJS - Page redirecting to some other page in angular js while trying to get parameter from url

Here's my controller code
.when('/showprofile/:UserID', {
templateUrl: 'resources/views/layout/showprofile.php',
controller: 'ShowOrderController',
})
I am passing the parameter by url.
I am trying to access this page by the url directly like this
http://192.168.1.58/myapp/#/showprofile/8
But it is redirecting me to
http://192.168.1.58/myapp/#/showprofile/:UserID
How can i get the url value in my view ?
Here is my app.js and here is my authCtrl.js
Try this in your controller, it will return the object based on url value then we can get the respected value like this
//it will return the object
console.log($routeParams);
//get the specific url value like this
console.log($routeParams.UserID);
or
console.log($route.current.params.UserID);
Yes possible but you have to inject the $state in your controller and get
if you use $state means
console.log($state.params.userID);
Try this...
var sampleApp = angular.module('sampleApp', []);
sampleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/ShowOrder/:orderId', {
templateUrl: 'templates/show_order.html',
controller: 'ShowOrderController'
});
}]);
sampleApp.controller('ShowOrderController', function($scope, $routeParams) {
$scope.order_id = $routeParams.orderId;
});
Right, you have something like this in app.js:
.when('/showprofile/:UserID', {
templateUrl: 'resources/views/layout/showprofile.php',
controller: 'authCtrl',
})
That means that authCtrl is assigned to this view.
So, it's neccessary to inject routeParams to authCtrl( remember about dependency injection in javascript ) :
app.controller('authCtrl', ['$scope','$rootScope','$routeParams','$location', '$http', 'Data', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
$scope.myVar = $routeParams.UserID;
console.log('UserID: ',$scope.myVar);
/* (...) */
}]);
Could you tell me, if this change, logs UserID in console? Or is empty?
If it logs, then everything works fine and you can use service to pass this variable between various controllers.

create basic object with $resource

I have been all over the tutorial sites and couldn't get this working
I'm trying to make an angular app that works over the REST with my server(I downloaded this and managed to get it working but I started a new one from scratch to understand everything better). making the REST server was the easy part since I'm a php guy, but I'm not so familiar with angular part.
I made a simple directory with yeoman and put my REST server next to it in another folder, so I have :
root
------app with all angular code here
------engine which is a yii2 framework
in app/script/app.js I have:
'use strict'; // BTW what is this line doing?
var app = angular
.module('gardeshApp', [
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/post/index' , {
templateUrl: 'views/post/index.html',
controller : 'PostList'
})
.otherwise({
redirectTo: '/'
});
});
I wanted make some kind of Model object to put received data in, so I created a Post model like :
app.factory('Post' , ['$resource'] , function($resource){
var Post = $resource('http://localhost/testApp/engine/web/post/:id' , {id : '#id'} , {update: {method: 'PUT'}});
angular.extend(Post.prototype , {
save: function (values) {
if (values) {
angular.extend(this, values);
}
if (this.id) {
return this.$update();
}
return this.$save();
}
});
});
and a controller to fetch the data:
app
.controller('PostList', ['$scope', '$http' , '$resource',
function($scope, $http) {
// $http.get('http://localhost/testApp/engine/web/post').success(function(data){
// console.log(data); // this works fine and gets the json ed data
// });
var posts = new Post();
console.log(posts.query());
}]);
I don't want to call $http.get myself, I want to make it dynamic but the Error says Post is not defined.
how can I make a proper Post Object to represent the model I'm fetching?
You may do something like this:
app.factory('Post' , ['$resource'] , function($resource){
var Post = $resource('http://localhost/testApp/engine/web/post/:id',
{
update: {method: 'PUT'}
}
);
return Post;
});
And,
app.controller('PostList', ['$scope', '$http' , 'Post',
function($scope, $http, Post) {
console.log(Post.query());
}]);
You need to return your built object in a factory in order to make it dependency-injectable later. Then in your controller, you need to declare that your want Post, and Angular will inject it for you.

Multiple Controllers for one view angularjs

I would like to know if it is possible to use multiple controllers for a single url view using angluarjs, I have not been able to find much documentation on this. I would like to use a controller on all pages to switch the page header title, but some pages already contain a controller
app.js
subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).
//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).
when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);
EDIT
I am trying to add a title controller to each page view:
function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }
If I add this controllers to the pages that don't already have a controller it works, if there is another controller in place I can't make this work.
<h1 ng-bind="header"></h1>
Yes, controllers and templates are independent, check this http://jsbin.com/wijokuca/1/
var app = angular.module("App", ['ngRoute']);
app.config( function ( $routeProvider ) {
$routeProvider
.when('/a', {templateUrl: 'this.html', controller: "aCtrl"})
.when('/b', {templateUrl: 'this.html', controller: "bCtrl"})
.when('/c', {templateUrl: 'that.html', controller: "bCtrl"})
.otherwise({redirectTo: '/a'});
});
app.controller('aCtrl', function ($scope) {
$scope.all = [1,2,3];
});
app.controller('bCtrl', function ($scope) {
$scope.all = [4,5,6];
});

Categories

Resources