I'm struggling to make my category and vendor name visible on breadcrumbs.
I'm using ng-breadcrumbs module (https://github.com/ianwalter/ng-breadcrumbs).
I guess I have problem with making curCategory and curVendor globally acessible, but tried some ways and can't make it working.
Here is my html:
<body ng-controller="mainController as main">
(...)
<ol class="breadcrumb">
<li ng-repeat="breadcrumb in breadcrumbs.get({'Category':curCategory,'Vendor': curVendor}) track by breadcrumb.path" ng-class="{ active: $last }">
<a ng-if="!$last" ng-href="#{{ breadcrumb.path }}" ng-bind="breadcrumb.label" class="margin-right-xs"></a>
<span ng-if="$last" ng-bind="breadcrumb.label"></span>
</li>
</ol>
My routes:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/pages/main.html',
label: 'Home'
}).
when('/:cat', {
templateUrl: 'templates/pages/category.html',
label: 'Category'
}).
when('/:cat/:ven', {
templateUrl: 'templates/pages/vendor.html',
label: 'Vendor'
}).
otherwise({
redirectTo: '/'
});
}]);
My controller:
var app = angular.module("myApp", [
'ngRoute',
'ng-breadcrumbs'
]);
app.controller('mainController', function($scope, $routeParams, breadcrumbs) {
$scope.breadcrumbs = breadcrumbs;
$scope.curCategory = $routeParams.cat;
$scope.curVendor = $routeParams.ven;
(...)
});
Uff I found what was wrong!
What suprised me was that inside specific controllers it worked fine, but when I moved it to mainController it returned empty object from $routeParams.
Here is solution:
$scope.$on('$routeChangeSuccess', function() {
$scope.curCategory = $routeParams.cat;
$scope.curVendor = $routeParams.ven;
});
It just assigned variables before $routeParams were populated.
Related
Maybe someone will help me. I write an app in angularjs, I have a file named list.html which retrieves a list of posts from jsonplaceholder and lists them, with a link to the details of the post. In $ routeParams, I pass the id of the selected one and pick it up. Unfortunately, I have no idea how to download the details of a post and display them in the details.html file. If I want to remove something for example, I write for example $ scope.deletePost as a function and give an id, but how to list details I have no idea.
//routing.js
var myApp = angular.module('myApp', ["ngRoute"])
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/event/example.html',
controller: 'exampleController'
}, null)
.when('/list', {
templateUrl: '/event/list.html',
controller: 'exampleController'
}, null)
.when('/test-list', {
templateUrl: '/test/list.html',
controller: 'testController'
}, null)
.when('/test/:id', {
templateUrl: '/test/details.html',
controller: 'testController'
}, null)
}
]);
//controller.js
angular.module('myApp').controller('testController', function ($scope, $http, $routeParams) {
$http.get('https://jsonplaceholder.typicode.com/posts').then(function (response) {
$scope.posts = response.data;
});
$scope.id = $routeParams.id;
});
//details.html
<div data-ng-controller="testController">
{{data}}
</div>
//list.html
<div data-ng-controller="testController">
<ul>
<li ng-repeat="post in posts">
Tytuł: {{post.title}} <a href="#!test/{{post.id}}" >Show</a>
</li>
</ul>
</div>
Check out this plunkr.
You just need to pass the details using ng-href and then catch in the controller using $routeParams. I hope this would help you with what you were looking for.
var app = angular.module( 'mainApp', ['ngRoute'] );
app.config( function( $routeProvider ) {
$routeProvider
.when( '/main', {
templateUrl: 'list.html',
controller: 'listCtrl'
})
.when('/detail/:id', {
templateUrl: 'detail.html',
controller: 'detailCtrl'
})
.otherwise({
redirectTo: '/main'
});
});
app.controller( 'listCtrl', function( $scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(res){
$scope.data = res.data;
})
});
app.controller( 'detailCtrl', function( $scope,$http, $routeParams) {
$scope.id = $routeParams.id;
$http.get('https://jsonplaceholder.typicode.com/posts/'+$scope.id)
.then(function(res){
$scope.data = res.data;
})
});
I'm teaching myself some AngularJS and have made some progress.
The routing on the following project doesn't seem to work but I don't know what I'm doing wrong. I use WebStorm.
I did an exercise (the adding names part) and now I'm trying to show what's within the views on the index page but this doesn't seem to work..
Index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="angular/angular.js"></script>
<script src="angular/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="myController as ctrl">
<h1>Lijst met namen</h1>
<input type="text" placeholder="voornaam..." ng-model="ctrl.voornaam">
<input type="text" placeholder="achternaam..." ng-model="ctrl.name">
<input type="button" value="Persoon toevoegen" ng-click="ctrl.addNaam()">
<ul>
<li ng-repeat="person in ctrl.personen">
{{person.name}} {{person.voornaam}}
</li>
</ul>
</div>
<div role="navigation">
<nav>
Home
About us
Contact us
</nav>
</div>
<div ng-view></div>
<script src="controller.js"></script>
<script src="aboutController.js"></script>
<script src="contactController.js"></script>
<script src="homeController.js"></script>
</body>
</html>
App.js:
angular.module('myApp',['ngRoute']).config(moduleConfig);
//Inject dependencies
moduleConfig.$inject = ['$routeProvider'];
//routes configureren
function moduleConfig($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home.html',
controller: 'homeController',
controllerAs: 'homeCtrl'
})
.when('/home', {
templateUrl: 'views/home.html',
controller: 'homeController',
controllerAs: 'homeCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'aboutController',
controllerAs: 'aboutCtrl'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'contactController',
controllerAs: 'contactCtrl'
})
.otherwise({
redirectTo: '/'
});
} })();
Controller.js:
angular.module('myApp', []).controller('myController', myController);
function myController(){
var vm = this;
vm.personen = [
{name: 'Schrooten', voornaam: 'Mathias'}
];
vm.addNaam = function(){
var newName = {
voornaam: this.voornaam,
name: this.name
};
this.personen.push(newName);
window.alert('Persoon toegevoegd!')
}
}
aboutController:
angular.module('myApp').controller('aboutController', aboutController);
function aboutController(){
this.msg = 'Hello';
}
2 other controllers look almost the same (contactController.js and homeController.js)
views:
about.html:
<div>
<p>About us: ....</p>
<input type="text">
</div>
Same for 2 other views.
this line angular.module('myApp', []) initializes a module.
So basically you have to initialize once.
then you can use it like this angular.module('myApp')
so this in you code:
angular.module('myApp', []).controller('myController', myController);
has to become like the line below because you already have myApp module defined:
angular.module('myApp').controller('myController', myController);
The angular.module('myApp') is a redundant code in your codebase. creating angular modules everywhere is the incorrect thing here. Create it once, store it in a variable, lets say 'app' and use it everywhere else.
Like as follows:
in app.js :
var app = angular.module('myApp', ['ngRoute']);
in route.js :
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'login.html'
})
.when('/home', {
templateUrl : 'main.html',
controller: 'myController'
})
.otherwise({
redirectTo: '/'
});
});
In Controller.js :
app.controller('myController', myController);
function myController(){
var vm = this;
vm.personen = [
{name: 'Schrooten', voornaam: 'Mathias'}
];
vm.addNaam = function(){
var newName = {
voornaam: this.voornaam,
name: this.name
};
this.personen.push(newName);
window.alert('Persoon toegevoegd!')
}
}
You can refer to one of my github repositories to understand a basic angular framework that uses template routing for a single page application here.
Try to do:
angular.module('myApp',['ngRoute']).config(['$routeprovider', moduleConfig]);
And then you should be able to get rid of the .$inject you call.
From your code as first I see this line looks to be wrong, when you register your 'myController' controller. There you are using angular.module('myApp', []) hovewer in App.js there is the 'myApp' module created. In 'Cotnroller.js' use angular.module('myApp').controller(...) without brackets. Currenlty in Controller.js you overwrite the 'myApp' module.
I'm new to AngularJS and stuck on below code.
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/home.html",
controller: "mainController",
})
.when('/products', {
templateUrl: "partials/productlist.html",
//controller: "ProductController",
})
.when('/product/:prodID', {
templateUrl: "partials/product.html",
controller: "viewController",
})
.when('/contact', {
templateUrl: "partials/contact.html",
controller: "contactController",
})
.otherwise({
redirectTo: "/"
});
});
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams){
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
And my product.html page code will look like this.
<div ng-controller="viewController">
<ol class="breadcrumb">
<li>Home</li>
<li>Products</li>
<li class="active">{{eachproduct.link}}</li>
</ol>
<div class="col-md-4">
<figure><img ng-src="{{ }}"></figure>
<p>
Read More
</p>
</div>
</div>
Problem is when I navigate to any product page value of {{eachproduct.link}} is not showing.
Any solution will be appriciated.
Use $rootScope instead of $scope
$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.
Sample :
controller('viewController',['$scope','$routeParams', '$http','$rootScope',function($scope,$routeParams, $http,$rootScope){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$rootScope.eachproduct = $scope.datap[$routeParams.prodID];
});
}]);
app.controller('ProductController', function($scope, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, $http){
$http.get('partials/productTable.json').success(function(response){
$scope.datap = response.lists;
$scope.eachproduct = $scope.datap[$routeParams.prodID];
});
});
It seems like what you are looking for is an angular provider such as a factory to store the values in, this will allow the values to be pass values around the controllers while using the routes.
Have a look at this example, while it isn't using routes, the principal is the same:
https://jsbin.com/wiwejapiku/edit?html,js,output
For more information on providers have a look here:
https://docs.angularjs.org/guide/providers
Your example would work something like this:
app
.factory('productFactory',function(){
return {
data: {}
};
})
.controller('ProductController', function($scope, $http, productFactory){
$scope.productFactory = productFactory;
$http.get('partials/productTable.json').success(function(response){
$scope.productFactory.data = response.lists;
});
}).
controller('viewController',function($scope,$routeParams, productFactory){
$scope.productFactory = productFactory;
$scope.eachproduct = $scope.productFactory.data[$routeParams.prodID];
});
Note you would also have to change your view to reference 'productFactory.data' respectively.
I have a LanguageSwitcher service and a LanguageSwitcher.switchLanguage() function that I can use to switch Language between french and english.
I am now trying to use a ui-router state to execute that function and it seems to work because I can see a 'translated' class (it toggles between 'french' and 'english') change in the markup when inspecting BUT the page goes blank like it's trying to load a view that is not there or something.
So I would like to prevent this behaviour and simply execute the function 'without changing the state' if possible.
<a ui-sref="language">Toggle</a>
Here is the ui-router config:
'use strict';
(function() {
angular.module('frontApp')
.run(['$rootScope', '$state', '$stateParams', function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}]
)
.config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function($urlRouterProvider, $stateProvider, $locationProvider){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/views/home.html',
controller: 'HomeCtrl'
})
.state('home.rules', {
url: '^/rules',
templateUrl: '/views/rules.html'
})
.state('home.terms', {
url: '^/terms',
templateUrl: '/views/terms.html'
})
.state('home.faq', {
url: '^/faq',
templateUrl: '/views/faq.html'
})
.state('language', {
controller: ['LanguageSwitcher', function(LanguageSwitcher) {
LanguageSwitcher.switchLanguage();
}]
});
$locationProvider.html5Mode(true);
}]);
}());
This is because my menu is dynamic and the toggle is not the last item of the navbar:
<header ng-controller="NavbarCtrl">
<h1><a class="navbar-brand" ui-sref="home">{{ 'siteTitle' | translate }}</a></h1>
<ul class="nav navbar-nav navbar-right">
<li ng-repeat="item in menu" ui-sref-active="active">
<a ui-sref="{{item.state}}" ng-href="{{item.link}}">{{item.title}}</a>
</li>
</ul>
</header>
The navbar.js file:
'use strict';
(function() {
angular.module('frontApp').controller('NavbarCtrl', ['$scope', '$translate', '$location', '$rootScope', function ($scope, $translate, $location, $rootScope) {
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['linkHome', 'linkRules', 'linkTerms', 'linkFAQ', 'language', 'otherLanguage', 'linkMainSite']).then(function (translations) {
$scope.menu = [
{
'title': translations.linkHome,
'link': '/',
'state': 'home'
},
{
'title': translations.linkRules,
'link': '/rules',
'state': 'home.rules'
},
{
'title': translations.linkTerms,
'link': '/terms',
'state': 'home.terms'
},
{
'title': translations.linkFAQ,
'link': '/faq',
'state': 'home.faq'
},
{
'title': translations.language,
'link': '/'+translations.otherLanguage,
'state': 'language'
},
//{
// 'title': translations.linkMainSite,
// 'link': 'http://'+translations.linkMainSite,
// 'state': ''
//}
];
//$scope.isActive = function(route) {
// return route === $location.path();
//};
});
});
}]);
}());
What I am missing? Many thanks for your time and help.
Based on the problem being how to use ng-repeat for the menu links, one suggestion would be using ng-if to create a different link for language that uses ng-click to manage the switching and not set any href attributes for it
Something like
<li ng-repeat="item in menu" ui-sref-active="active">
<a ng-if="item.state !== 'language'" ui-sref="{{item.state}}" ng-href="{{item.link}}">{{item.title}}</a>
<a ng-if="item.state === 'language'" ng-click="switchLang()">{{item.title}}</a>
</li>
Then in NavbarCtrl controller have switchLang() make the call to your language service
This is inferred in many of the comments from your post: there is no reason to use a state to call the language switcher.
Instead you probably just want to include the controller in your menu using ng-controller, or create a component/directive, and call the service method through the using ngClick.
I am currently building a Angularjs singel page application and i have run in to some odd error with my routing.
I have a nav bar with multiple options and all but one of them work correct.
This is my route provider.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/index", {
templateUrl: "/App/Views/index.html",
controller: "IndexController"
})
.when("/log", {
templateUrl: "/App/Views/log.html",
controller: "LogController"
})
.when("/help", {
templateUrl: "/App/Views/help.html",
controller: "HelpController"
})
.when("/login", {
templateUrl: "/App/Views/login.html",
controller: "LoginController"
})
.when("/signup", {
templateUrl: "/App/Views/signup.html",
controller: "SignupController"
})
.when("/logout", {
templateUrl: "/App/Views/logout.html",
controller: "LogOutController"
})
.when("/user", {
templateUrl: "/App/Views/user.html",
controller: "UserController"
})
.otherwise({
redirectTo: "/index"
});
}]);
And this is my Navbar
<li>
Hem
</li>
<li ng-class="{ activeLink: isActive('/log')}" data-ng-hide="!isLoggedIn">
Logg
</li>
<li ng-class="{ activeLink: isActive('/help')}" data-ng-hide="!isLoggedIn">
Hjälp
</li>
<li ng-class="{ activeLink: isActive('/logout')}" data-ng-hide="!isLoggedIn">
Logga ut
</li>
<li ng-class="{ activeLink: isActive('/user')}" data-ng-hide="!isLoggedIn">
{{userName}}
</li>
And my problem is that when i click the {{userName}} link i am taken to the index page.
And this error only occurs on the live server when the js is minified, if it is unminified on the server so does it work like intended.
If i run this site localy i can use both the regular version and the minified one and the routing behaves like intended.
The console does not show any errors when i click on the link and whn i inspect the html in chrome so does it have the correct html
Johan Karlsson.
I have tried pointing the {{userName}} link to "#/log" and it worked fine.
Here is my user controller
(function () {
var app = angular.module("connectPortal");
var userController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from HelpController";
}];
app.controller("UserController", userController);
}());
And this is my log controller
(function () {
var app = angular.module("connectPortal");
var logController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from LogController";
}];
app.controller("LogController", logController);
}());