Dynamic route and controller with ng-class - javascript

I'm try to create dynamic framework with angularjs
here is my plan ... the user have to add the new templateUrl and controller from json file like this templates.json
{
"pages" : [
{
"name" : "home",
"tempUrls" : "views/home",
"controller" : "HomeController"
},
{
"name" : "about",
"tempUrls" : "views/about",
"controller" : "AboutController"
},
{
"name" : "contact",
"tempUrls" : "views/contact",
"controller" : "ContactController"
}
]
}
from here our job to create for hem the controller and templateUrl with the page name in angularjs like this hours.js
var hours = angular.module('hours', ['ngRoute']);
var $routeProviderReference;
var currentRoute;
hours.config(function($routeProvider){
$routeProviderReference = $routeProvider;
})
.run(['$route', '$http', '$rootScope', function($route, $http, $rootScope){
$http.get("templates.json").success(function(data){
var loop = 0, currentRoute;
for(loop = 0; loop < data.pages.length; loop++){
currentRoute = data.pages[loop];
var routeName = "/" + currentRoute.name;
$routeProviderReference.when(routeName, {
templateUrl: currentRoute.tempUrls,
controller : currentRoute.controller,
resolve: {
param: function()
{
return currentRoute.resolve;
}
}
});
}
$route.reload();
});
}]);
hours.controller(currentRoute.controller, function($scope){
$scope.pageClass = 'page-' + currentRoute.name;
});
and here is the index.html
<div ng-class="{{pageClass}}" ng-view></div>
and here is the static version from angularJS before i converted to dynamic
var hours = angular.module('hours', ['ngRoute']);
hours.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'views/page-home.html',
controller: 'homeController'
})
});
hours.controller('homeController', function($scope){
$scope.pageClass = 'page-home';
});
i hope really someone can help!!!

This is how I am used to working with ng-class. It does appear to have multiple formats. This style requires single curly braces.
ng-class="{ myClass: ExpressionThatResolvesTrueOrFalse }"
So if the expression resolves true, then Angular will add myClass to the element. If it resolves false, it will not add the class. It will watch the value of the expression for changes as part of the normal scope digest.
I believe the model format does not use braces at all and is more like:
ng-class="pageClass"

Related

AngularJS routing , how to pass parameter with a url of view

i want to pass parameter id with url in angularJS ,
i try in home.config :
home.config(["$routeProvider",function ($routeProvider) {
$routeProvider
.when("/profile",{
templateUrl : "views/home/profile.html",
controller : "profile"
})
.when('/settings',{
templateUrl : "views/home/settings.html",
controller : "Settings"
})
.when('/item',{
templateUrl : "views/home/item.html",
controller : "item"
});
}]);
in home.html :
<a href="#!item?id='+Item_id+'" >Item View</a>
and in itemController
controllers.controller("item",function ($scope,$http,$rootScope) {
var url_string = window.location.href; // home.php#!/item?id=0ae8b2fc-3ccb-11e8-952b-708bcd9109ce
var url = new URL(url_string);
var item_id = url.searchParams.get("id");
console.log(item_id);
})
but I get a null value, please help thanks in advance .
If you are using ngRoute you should use $route in the controller to get the parameters of the route.
You can see working code here:
const app = angular.module("mainapp", ["ngRoute"]);
app.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/profile", {
template: "<p>profile</p>",
controller: function() {}
})
.when('/settings', {
template: "<p>settings</p>",
controller: function() {}
})
.when('/item', {
template: "<p>item {{itemid}}</p>",
controller: function($route, $scope) {
$scope.itemid = $route.current.params.itemid;
}
});
}]);

how to change angularjs controller name

I am just beginner in angularjs I want to change angularjs controller name according name is written with templateUrl.
Here is example
.when({ templateUrl:'template.html',controller:'mycontrollername'})
and now I want to send above controller name at bellow controller name.
app.controller('6th-septemberCtrl', ['$scope','$http','filterFilter', function ($scope,$http, filterFilter) {});
I have many controllers like this so want to send controller name according which route templateUrl is click imigiatily change the controller name and should worked as written like same default way
I would create one static class which will hold the controller names per template.
Use the same class to get the names of the controller. Here is my example in code.
var app = angular.module("plunker", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "main.htm",
controller: getControllerName('main.htm')
})
.when("/red", {
templateUrl: "red.htm",
controller: getControllerName('red.htm')
})
.when("/green", {
templateUrl: "green.htm",
controller: getControllerName('green.htm')
});
});
function getControllerName(url) {
for(var i=0; i<templateControllers.length; i++) {
if(templateControllers[i].url === url)
return templateControllers[i].controllerName;
}
}
var templateControllers = [{
url: 'main.htm',
controllerName: 'mainController'
}, {
url: 'red.htm',
controllerName: 'redtroller'
}, {
url: 'green.htm',
controllerName: 'greenController'
}];
//create controller for main url
app.controller(getControllerName('main.htm'), function($scope) {
$scope.name = 'main';
});
//create controller for red url
app.controller(getControllerName('red.htm'), function($scope) {
$scope.name = 'red';
});
//create controller for green url
app.controller(getControllerName('green.htm'), function($scope) {
$scope.name = 'green';
});

Angularjs pass query parameter

Right now I'm calling below code :
http://localhost:8081/cgi/#/home
And it takes me to my home page.
My app.js is :
angular.module('myModule',
['ngRoute', 'ngCookies', 'ui.bootstrap',
'angularUtils.directives.dirPagination'])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/index', {
controller : 'homeController',
templateUrl : './app/views/index.html',
})
.when('/', {
controller : 'homeController',
templateUrl : './app/views/home.html'
})
.otherwise({
redirectTo : '/'
});
}])
Now I need to add extra parameter "debug", which I can store in my controller and if it is there I need to call some function.
I have tried adding below to my app.js
.when('/debug', {
controller : 'homeController',
templateUrl : './app/views/home.html',
})
and below line to my controller
$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);
in my controller :
var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route) {
$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);
}
Also please include url you think would work in answer as I can understand from where to start looking for either routeProvider or $location functionality
But page has now stopped loading and I don't have any clue how can I make it work.
Please help
You need to inject the $routeParams service to the controller. Just add it as a parameter to the controller function.
var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route, $routeParams) {
$scope.debug = $routeParams.debug === 'true' ? true : false;
console.log($scope.debug);
}
--- Update ---
Path
Use $location.path() === '/debug' to check if the current path is '/debug'. You need to inject the $location service.
var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route, $location) {
$scope.debug = $location.path() === '/debug';
console.log($scope.debug);
}
Query Param
This will allow you to check if there is a query parameter keyed "debug" with the value of "true".
http://localhost:8081/cgi/#/home?debug=true
 
var app = angular.module('myModule');
app.controller('homeController', function($scope, $http, $route, $location) {
$scope.debug = $location.search().debug;
console.log($scope.debug);
}

Information doesn't refresh after clicking on link in AngularJS. I've got {{ value }} but not the data

I have an Angular app that takes information from few JSON files.
The first JSON file contains data about cities and managers. Like this:
[
{
"link" : "veliky_novgorod",
"city" : "Великий Новгород",
"manager" : "mr. Sminth",
},
{
"link" : "magnitogorsk",
"city" : "Магнитогорск",
"manager" : "mr. Young",
},...
I use it in order to create a page for every city.
My urls look like this: ...index.html#/cities/veliky_novgorod/, ...index.html#/cities/biisk/, ...index.html#/cities/biisk/mobile/, etc.
Everything works fine, but when I try to go from one page to another information from the other JSON (scopes) doesn't load. After changing page I've always got {{ value }}
But when I make refresh manually, everything is going back to normal.
In other words, how can I reload new page after clicking on link. I tried to use window.location.reload() But it doesn't work.
<li ng-repeat="city in cities">
{{city.manager}}
</li>
My module and controller below:
var curryApp = angular.module('CurryApp', [
'ngRoute',
'curryControllers'
]);
curryApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'link_list.html',
controller: 'CurryListCtrl'
}).
when('/cities/:cityId/', {
templateUrl: 'template-total.html',
controller: 'CurryDetailCtrl'
}).
when('/cities/:cityId/mobile/', {
templateUrl: 'template-mobile.html',
controller: 'CurryMobileCtrl'
}).
otherwise({
redirectTo: '/'
});
}]);
That's my controller:
var curryControllers = angular.module('curryControllers', []);
curryControllers.controller('CurryListCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('cities.json').success(function(data) {
$scope.cities = data;
});
}]);
curryControllers.controller('CurryDetailCtrl', ['$scope', '$routeParams', '$http', '$route',
function($scope, $routeParams, $http, $route) {
$scope.reloadRoute = function(){window.location.reload();}
$scope.cityId = $routeParams.cityId;
$http.get('cities.json').success(function(data) {
$scope.cities = data;
$http.get('paidbc.json').success(function(data2) {
$scope.paidBc = data2;
$scope.isActive = function(item) {
return item.link === $scope.cityId;
};
});
});
}]);
curryControllers.controller('CurryMobileCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
$scope.cityId = $routeParams.cityId;
}]);
It seems that is an error related with the href attribute. According to docs:
The wrong way to write it:
link1
The correct way to write it:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
In your case, use:
<a ng-href="#/cities/{{city.link}}" ng-click="reloadRoute()">{{city.manager}}</a>
instead of using only href.

Angular Directive update view from template url

I have started learning angularjs recently and I am doing some stuff. I tried to use this actice example, especially 3 example. I tried to read from tempate files by their url but I couldn't. I got bellow code (here only peace of code which I changed):
var app = angular.module('app', []);
app.value('MultiViewPaths',
{'/' : {
content : {
templateUrl : './templates/_header.html'
},
secondaryContent : {
templateUrl : './templates/_secondaryContent.html',
controller : 'ListUsersCtrl'
}
},
'/cats' : {
content: {
templateUrl : 'templates/_headerCats.html',
controller : 'ListCatsCtrl'
},
secondaryContent : {
templateUrl : 'templates/_secondaryContentCats.html',
controller : 'CatOfTheMinuteCtrl'
}
}
});
app.directive("ngMultiView", ['$rootScope', '$compile', '$controller', '$location', 'MultiViewPaths','$templateCache', function($rootScope, $compile, $controller, $location, MultiViewPaths, $templateCache){
var getTemplate = function(templateUrl) {
console.log(templateUrl)
var template = $templateCache.get(templateUrl);
console.log(template)
return template
}
return {
terminal: true,
priority: 400,
transclude: 'element',
compile : function(element, attr, linker){
return function(scope, $element, attr) {
var currentElement,
panel = attr.ngMultiView;
$rootScope.$on('$locationChangeSuccess', update);
update();
// update view
function update(evt, newUrl, oldUrl){
if(!newUrl){ return }
var url = newUrl.match(/#(\/.*)/),
match, template, controller;
match = url ? MultiViewPaths[url[1]] : MultiViewPaths['/'];
template = getTemplate(match[panel].templateUrl);
console.log(template)
controller = match[panel].controller;
if(template){
var newScope = scope.$new(),
locals = {},
newController = controller;
linker(newScope, function(clone){
clone.html(template);
$element.parent().append(clone);
if(currentElement){
currentElement.remove();
}
var link = $compile(clone.contents());
currentElement = clone;
if (newController) {
locals.$scope = newScope;
var controller = $controller(newController, locals);
clone.data('$ngControllerController', newController);
clone.children().data('$ngControllerController', newController);
}
link(newScope);
newScope.$emit('$viewContentLoaded');
});
}else{
//cleanup last view
}
}
}
}
}
}]);
Other thing the same with example. I could not read templates inner html. Can anyone help me ?
I would recommend using uiRouter rather than ngRouter. With uiRouter you do not need to create a directive to handle changing the view for different URL parameters.
They give an example of how to do this using the $stateProvider here http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider
templateUrl: function(params) {
return myTemplates[params.pageId]; }

Categories