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.
Related
I'm stuck with nested states in the ui-router.
I'm rendering a page with regions, countries and people per country
The index.html has three regions as link, EMEA APAC and AMER
the part of the index page has:
<a ui-sref="territory({territory: 'amer'})">AMER</a> <a ui-sref="territory({territory: 'emea'})">EMEA</a> <a ui-sref="territory({territory: 'apac'})">APAC</a>
<ui-view></ui-view>
when the link is clicked, the countries are returned by a $http.post action and displayed by /views/countries.html as:
<h1>This is countries</h1>
<br>
Teritory: {{region}}
<div ng-repeat='country in countries'>
<a ui-sref=".support({country: '{{country}}'})">{{country}}</a ui-sref>
</div>
This is working so far! so I have a .support link on each country.
The problem is now, when I click the link, the state is accepted...cause it is loading the templateURL, but it seems that the controller specified in that state is not loaded.
the angularjs code:
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
controller: 'supportCtrl'
})
.state('territory', {
url: '/territory/:territory',
templateUrl: 'views/countries.html',
controller: 'countryController'
})
.state('territory.support',{
url: '/:country',
templateUrl: 'views/supporter.html',
controller: 'supportController'
})
});
the support controller is writing a console.log entry...but nothing happens.
the controllers:
supportApp.controller('countryController',['$scope', 'supportService', '$location', '$stateParams', function($scope, supportService, $location, $stateParams){
$scope.fromTerritory = $stateParams.territory;
$scope.getCountries = function(){
var countries = supportService.getCountries($scope.fromTerritory);
countries.then(function(response){
if(response.data.error){
$scope.error = true;
$scope.message = response.data.message;
}
else{
console.log('response OK');
$scope.region = $scope.fromTerritory;
$scope.countries = response.data;
}
});
}
$scope.getCountries();
}]);
supportApp.controller('supportController',['$scope', 'supportService', '$location', '$stateParams', function($scope, supportService, $location, $stateParams){
console.log('in the supportController');
var test = function(){
console.log('supportController country: '+$stateParams.country);
}
test();
}]);
I'm probably doing something wrong here.
The goal is clicking the country and then displaying names of the people belonging to that specific country.
If it's not clear, I can provide more info where needed. But for now it seems that the controller (supportController) for the nested state (.territory.support) is not running / loaded
thank you!
Ok,
I have my answer for now...
because I did not use the <ui-view></ui-view> on the supporter.html the controller was not 'needed' and did not load.
after adding the the consol.log is showing the log entries.
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.
I've been creating a contact list website and have just begun trying to implement an add contact function. So far I have created the page using a form and input elements and then use ng-click to call a function which theoretically would add an object containing these input values into an already-existing array in the controller. For some reason this doesn't work and nothing is added.
In particular, I'm having trouble with the js/app.js file and the $scope.saveContact = function() in relation to the partial/edit.html webpage. Clicking the "Confirm button" when trying to add a contact calls the saveContact function, but the results are not stored properly. Any help is appreciated.
In my HTML I have this code (which calls the saveContact() function in my controller.
<a href="#/"><div class="confirm col-xs-6" ng-click="saveContact()">
<h3>Confirm</h3>
</div></a>
In my app.js file I have a declaration of an empty object and an array containing objects that already have values (used to display the contacts that are already created). I'm trying to add to these contacts using .push() but it for some reason it doesn't work.
$scope.contact = { ... } //empty object that gets inputs from HTML
$scope.contacts = [ { ... }, ... ];
$scope.saveContact = function(){
$scope.contacts.push($scope.contact);
};
This bottom function fails to push the contact object to the contacts array and I don't understand why.
This is happening as you have assigned same controller to all your routes. Your saveContact function is working fine, its pushing the object to the array. As soon as the route changes, a new instance of the controller is created and hence the added object is lost. You should create a service(singleton) to store the object and inject the service as a dependency to the controller. In this way the array will persist until the page load.
app.service("storeContact", function(){
var contacts = [];
this.setContact = function(cnt){
contacts.push(cnt)
};
this.getContact = function(){
return contacts;
}
});
And inject it in the controller and use the setContact and getContact methods to update the contact array and retrieve the contact array.
Ideally, you should have separate controllers for your route.
The issue is in your app.config code. You are using the same controller for all your templates.
This is not required since you have already mentioned the same in ng-controller attached with body
<body ng-controller="AppController">
<div ng-view></div>
<script src="js/app.js"></script>
</body>
Using same controller for all your routes is essentially (re)instantiating the controllers when the route is changed and thats the reason why $scope.contacts.push($scope.contact); is ineffective for the route / when called from /add.
contactListApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
controller: 'AppController',
controllerAs: 'list',
templateUrl: 'partials/list.html'
})
.when('/add', {
controller: 'AppController',
controllerAs: 'add',
templateUrl: 'partials/edit.html'
})
.when('/edit/:id', {
controller: 'AppController',
controllerAs: 'edit',
templateUrl: 'partials/edit.html'
})
.otherwise({
redirectTo: '/'
});
}]);
Workaround:
Either use separate controllers for separate routes and use a service to store the object
OR
Simply remove the controller and controller as from your route config and you are good to go.
Updated config:
contactListApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/list.html'
})
.when('/add', {
templateUrl: 'partials/edit.html'
})
.when('/edit/:id', {
templateUrl: 'partials/edit.html'
})
.otherwise({
redirectTo: '/'
});
}]);
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
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];
});