AngularJS - Passing ID from a page and populate in other page - javascript

I am new to AngularJS. In my project I have a search screen when search I will get the search result in the ngGrid.
On click of any row in the grid, it should populate the details of that row in other page. Basically, I need to pass the ID of the selected record to the other page. I don't know how to handle this in AngularJS (I am using AngularJS HotTowel template) and Breeze for data access logic.
Appreciate if you could provide me link or any where it is implemented which I could refer.

You can create service and share values for instance
var myApp = angular.module('myApp', []);
myApp.factory('ShareData', function() {
var shared;
return {
setValue: function(val){
shared = val;
},
getValue: function(){
return shared;
}
});
function FirstCtrl($scope, ShareData){
ShareData.setValue(1);
}
function SecondCtrl($scope, ShareData){
$scope.data = ShareData.getValue();
}

You need $routeParams for this.
Below is an example of the routing configuration:
var app = angular.module("app", ["ngRoute"])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
controller: "HomeController",
templateUrl: "/home/main",
})
.when("/products/:category", {
controller: "ProductController",
templateUrl: "/product/index"
})
.otherwise({
redirectTo: "/"
});
}]);
Product Controller
angular.module("app")
.controller("ProductController",["$scope","$routeParams", function($scope,$routeParams){
$scope.category = $routeParams.category;
alert($scope.category);
}]);
'Main' View
<a ng-href="#/products/ladies">Ladies</a>
check this URL for more info:
https://docs.angularjs.org/api/ngRoute/service/$routeParams

Related

How to change pages based on url

I wan't to be able to change pages based on url. My url's look like this http://todolist.com/#/1 where last number is page number. So far my pagination is working (angular ui bootstrap). If i try to change page with numbers or buttons in pagination row the pages will change based on response. But url are not changing in url bar and if i change url manually the pages won't change.
This is my controller
controllers.todoCtrl = function ($scope, $timeout, todoFactory, $location, $routeParams) {
if($routeParams.pageNumber == undefined || $routeParams.pageNumber == null){
$scope.currentPage = 1;
} else {
$scope.currentPage = $routeParams.pageNumber;
}
getData();
//get another portions of data on page changed
$scope.pageChanged = function () {
getData();
};
/**
* Get list of todos with pagination
*/
function getData() {
todoFactory.index($scope.currentPage).then(function (data) {
$scope.totalItems = data.paging.count;
$scope.itemsPerPage = data.paging.limit;
$scope.todos = data.Todos;
});
}
My routes
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/templates/todolists.html',
controller: 'todoCtrl'
}).when('/:pageNumber', {
templateUrl: 'app/templates/todolists.html',
controller: 'todoCtrl'
}).otherwise({ redirectTo: '/'});
What do i have to do to make pagination based on url working. If you need any additional information, please let me know and i will provide. Thank you
you can use the updateParams function of $route to update the url.
So your code would look like this:
//get another portions of data on page changed
$scope.pageChanged = function () {
//getData();
$route.updateParams({pageNumber: $scope.currentPage});
};
This will cause the url to change. However keep in mind that this will destroy and recreate your controller.
Personally I avoid using the build in Angular router and prefer to use UI-Router instead. UI-Router uses a state base approach with a nice clean interface
So in order to use UI-Router you have to grab it from here or install it with your favorite package manager.
Your routes would be configured like this:
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider) {
$stateProvider.state('home', {
url: '/',
templateUrl: 'app/templates/todolists.html',
controller: 'todoCtrl'
})
.state("details", {
url: '/:pageNumber',
templateUrl: 'app/templates/todolists.html',
controller: 'todoCtrl'
});
});
As you can see in the above sample, states get names with UI-Router. You can use those names later in your controllers and templates to reference the states. In addition to that you can have nested states.
Example in your controller:
controllers.todoCtrl = function ($scope, $timeout, todoFactory, $location, $state, $stateParams) {
if(!$stateParams.pageNumber){
$scope.currentPage = 1;
} else {
$scope.currentPage = $stateParams.pageNumber;
}
getData();
//get another portions of data on page changed
$scope.pageChanged = function () {
$state.go("details", {pageNumber: $scope.currentPage });
};
/**
* Get list of todos with pagination
*/
function getData() {
todoFactory.index($scope.currentPage).then(function (data) {
$scope.totalItems = data.paging.count;
$scope.itemsPerPage = data.paging.limit;
$scope.todos = data.Todos;
});
}

Routing is not working in AngularJS app

I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});

unable to pass data between the views in angularjs through routing

In my angularjs app, I am trying to pass the data from one cshtml view to another view through routing but in details.cshtml, I don't see the data coming into it though I can see the change in URL
Index.cshtml (View1)
{{addprodtocart}}
Controller.js
app.controller('CartController', function ($scope) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
$scope.cid = cartprd[len];
}
});
Details.cshtml ( I don't see the data coming into the span below)
<div ng-controller="CartController">
<span ng-model="cid">{{cid}}</span>
</div>
Myrouting
var app = angular.module("productmodule", ["ngRoute"]);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: '/Product/Details',
controller: 'CartController'
});
}]);
I created a plunker for this. I am unable to send the data from page1 to page2
http://plnkr.co/edit/micM7vlslznEIZXP293Y?p=preview
Your problem is your controller is instantiated again while clicking on href and the scope is getting recreated & $scope.cid is set to undefined.
You could achieve the same by using $routeParams which will give the access to what url contains
In your case it would be $routeParams.cid
Code
app.controller('CartController', function ($scope, $routeParams) {
$scope.SendToCartPage = function(cartprd)
{
var len = cartprd.length - 1;
//$scope.cid = cartprd[len];
}
$scope.cid = $routeParams.cid;
});
Update
You should use $routeParams service to get data from url
Code
var app = angular.module('plunker', ['ngRoute']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/Details/:cid', {
templateUrl: 'page2.html',
controller: 'CartController'
}).when('/', {
templateUrl: 'page1.html',
controller: 'CartController'
});
}
]);
app.controller('CartController', function($scope, $routeParams) {
$scope.myvar = $routeParams.cid; //this will asign value if `$routeParams` has value
console.log($scope.myvar);
$scope.Add = function(c) {
$scope.myvar = c;
}
});
Working Plunkr

Can .when be dynamically generated with Angular $routeProvider?

Have an app where admins create ITEMs for users to view. Each ITEM is a doc stored in Mongo.
The item.html view and ItemController.js are consistent for all the ITEMs..
The user is first presented an ITEM_list view..
..where the user can click on an ITEM divBox,
which would reveal the item.html view populated with the specific db content found for the selected ITEM
Is there a way to have angular do something like this in appRoutes.js
angular.module('appRoutes', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider
// start page listing all the ITEMs
.when('/', {
templateUrl: 'views/itemsList.html',
controller: 'ItemsListController'
})
// dynamic pages for each ITEM, once selected ?!
.when('/{{ITEM}}', {
templateUrl: 'views/item.html',
controller: 'ItemController'
});
$locationProvider.html5Mode(true);
}]);
You can use parameters in the route by using a colon before whatever variable name you want.
For example:
.when('/:itemID', {
templateUrl: 'views/item.html',
controller: 'ItemController'
}
Then in your ItemController, you can call that using $routeParams.
.controller('ItemController', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.itemID = $routeParams.itemID;
}]);
Here is the link to the Angular docs for some more guidance. http://docs.angularjs.org/tutorial/step_07
You can pass the item id, for example, like so:
.when('/item/:item_id', {
templateUrl: 'views/item.html',
controller: 'ItemController'
})
Then, in your controller, you can inject $routeParams:
.controller('ItemController', function($scope, $routeParams) {
var item_id = $routeParams.item_id;
});
Then, when they select, you set the location to /item/2 or whatever, and you know it is item 2 in your controller, so you can then either fetch that item from the server, or if you have a service with them already loaded you can figure out which one it is.

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