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.
Related
For example I have this input button:
<input type="button" class="blue-button pull-right" value="{{gb.gebruikerToevoegenText}} toevoegen" ng-click="gebruikers.addGebruiker()"/>
In the controller I am trying to achieve this through this logic:
vm.gebruikerToevoegenText = $location.path() == '/gebruikers' ? "Super User" : "Gebruiker";
But this guides me to same url for both views i.e. /gebruikers
I want its value to be different when the URL is /gebruikers/:id?/:naam?', below is the route definition:
$routeProvider.when('/gebruikers/:id?/:naam?', {
templateUrl: 'gebruikers.html',
controller: 'gebruikersController as gebruikers',
resolve: {
authentication: ['fwgAuthService', function (fwgAuthService) {
return fwgAuthService.login();
}]
}
});
$routeProvider.when('/gebruiker/:licentieHouderId/:id?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikerController as vm',
resolve: {
authentication: ['fwgAuthService', function (fwgAuthService) {
return fwgAuthService.login();
}]
}
});
I want to change user rights as well on this URL , but only if I know how to manipulate the view based on URL, I do not want to change the template, other wise it is going to be lots of copy and paste.
You'll have to change the template anyways. Please don't pollute the rootScope for this; you can use ng-if or ng-show/hide (as already suggested). Just add an isAuthorized() function to your controller and set a flag if the url matches a certain pattern. Moreover I would alter the controllerAs name to the same name for both path in order to make templating easier.
I checked the url by using the following function in the controller thanks for helping out:
vm.gebruikerToevoegenText = $routeParams.id ? "Super User" : "Gebruiker";
Index.html
<!doctype html>
<html ng-app="routerApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script>
var routerApp = angular.module('routerApp', ['ui.router', 'ngRoute']);
routerApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/gebruikers/:id?/:naam?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikersController'
}).
when('/gebruiker/:licentieHouderId/:id?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikerController'
}).
otherwise({
redirectTo: '/gebruikers/:id?/:naam?'
});
}]);
routerApp.controller('gebruikersController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.toevoegen = "Pratapsss";
}]);
routerApp.controller('gebruikerController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.toevoegen = "Pratap";
}]);
</script>
</head>
<body>
<div ng-view></div>
</body>
</html>
gebruiker.html
<div>
<input type="button" class="blue-button pull-right" ng-value="toevoegen" ng-click="gebruikers.addGebruiker()"/>
</div>
I'm trying to make an AngularJS application but I don't understand why it doesn't route correctly, I followed some guides but havenĀ“t made it work yet.
Here is the code:
index.html
<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
<meta charset="UTF-8">
<title>Example App</title>
</head>
<body>
<div ng-view></div>
<!-- Vendor libraries -->
<script src="lib/jquery-2.1.4.min.js"></script>
<script src="lib/angular.min.js"></script>
<script src="lib/angular-route.min.js"></script>
<!-- Application Files -->
<script src="app/app.js"></script>
<script src="app/home/controllers/HomeController.js"></script>
</body>
</html>
app.js
(function() {
'use strict';
var app = angular
.module('App', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/views/index.html',
controller: 'HomeController',
controllerAs: 'home'
})
.otherwise({
redirectTo: '/'
});
});
})();
HomeController.js
(function() {
'use strict';
angular
.module('App')
.controller('HomeController', HomeController);
function HomeController(){
var home = this;
}
})();
home's index.html
<div>
Example text
</div>
Thanks in advance
Are you seeing errors in the console? You're probably getting an error relating to the controller not being found, as 'home/controllers/HomeController' is not a proper way to reference HomeController. It should instead read: 'HomeController'. Angular will do the work to traverse your controllers and find one that matches that string.
Here's an updated app.js:
(function() {
'use strict';
var app = angular
.module('App', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home/views/index.html',
controller: 'HomeController',
controllerAs: 'home'
})
.otherwise({
redirectTo: '/'
});
});
})();
Additionally, in HomeController.js, you are re-instantiating the module 'App' by including the brackets after the name. Instead, modify it to more succinctly read:
(function() {
'use strict';
angular
.module('App')
.controller('HomeController', HomeController);
function HomeController(){
var home = this;
}
})();
I'm trying to create a simple website using angular as front-end.
Is there a way to create partial views and routing without having a webserver?
I've been trying to do so, but I keep getting this error:
Uncaught Error: [$injector:modulerr]
Here's my code: index.html
<!DOCTYPE html>
<html lang="en" ng-app="cerrajero">
<head>
<meta charset="UTF-8">
<title>Cerrajero</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
</head>
<body ng-controller="MainCtrl">
<div ng-view></div>
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
<script type="text/ng-template" id="partials/contact.html" src="partials/contact.html"></script>
<script type="text/ng-template" id="partials/services.html" src="partials/services.html"></script>
<script type="text/ng-template" id="partials/home.html" src="partials/home.html"></script>
</body>
</html>
and the app.js:
var app = angular.module('cerrajero', []);
app.config([function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
function MainCtrl ($scope) {
};
What am I doing wrong?
edit
I've added the ngRoute but I still get the same error when I open the index.html file in the browser.
var app = angular.module('cerrajero', ['ngRoute']);
app.config([function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
function MainCtrl ($scope) {
};
edit 2
Here's the files on github:
https://github.com/jsantana90/cerrajero
and here's the website when it loads:
http://jsantana90.github.io/cerrajero/
edit 3
I've manage to get rid of the error by having the following code:
var app = angular.module('cerrajero', ['ngRoute']);
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$locationProvider.html5Mode(false);
$routeProvider.
when('/services', {
template: 'partials/services.html'
}).
when('/contact', {
template: 'partials/contact.html'
}).
when('/home', {
template: 'partials/home.html'
}).
otherwise({
redirectTo: '/home',
template: 'partials/home.html'
});
}]);
app.controller('MainCtrl', function ($scope) {
});
I added this app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
But now my page is blank. It doesn't redirects or anything.
Have I placed everything how it's suppose to go?
edit 4
I forgot to change ui-view to ng-view. Now it works but it's showing in the view: partials/home.html instead of the actual view.
edit 5
Ok so, after having this final code:
var app = angular.module('cerrajero', ['ngRoute']);
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$routeProvider.
when('/services', {
templateUrl: './partials/services.html'
}).
when('/contact', {
templateUrl: './partials/contact.html'
}).
when('/home', {
templateUrl: './partials/home.html'
}).
otherwise({
redirectTo: '/home'
});
}]);
app.controller('MainCtrl', function ($scope) {
});
I get this error:
XMLHttpRequest cannot load file:///partials/home.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Now I'm guessing this is because I don't have a webserver running. How do I get it to work without a webserver?
solution
When I uploaded the files to github it seems to work there, but not locally.
Looks like you are using ngRoute and forgot to include it!
First load angular-route.js after loading angular.js. The inject ngRoute as a module:
var app = angular.module('cerrajero', ['ngRoute']);
Try removing the array syntax brackets from inside your config function. I believe there are two different ways of invoking these functions, either with a standalone function or with an array for any minification processes.
You should either one of the following:
app.config(function ($locationProvider, $routeProvider) {
// your code here
});
Or define the variable names with the array syntax for use in minifiers
app.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
// your code here
}]);
When you pass in an array to the config function, I believe Angular is expecting the first parameters to be a string value.
You should use ui-router instead of ng-route. It will allow you to nest views. Most current Angular projects use ui-router. ui-router scotch.io
Also, for your controller try app.controller('MainCtrl', function($scope){...});
Replace
var app = angular.module('cerrajero', []);
with
var app = angular.module('cerrajero', ['ngRoute']);
I am working with AngularJS and using the ngRoute for routing.
I was wondering if this is normal behavior for Angular when it routes to the "otherwise" part and activates all controllers?
var angularApp = angular.module('AngularApp', ['ngRoute']);
angularApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/ExpenseOverview', {
controller: 'ExpenseOverviewController',
templateUrl: 'Angular/Views/ExpenseOverview.vbhtml'
})
.when('/AddExpense',
{
controller: 'AddExpenseController',
templateUrl: 'Angular/Views/AddExpense.vbhtml'
})
.otherwise({ redirectTo: '/ExpenseOverview' });
}]);
I have put an alert at the very top in each controller, even my factory. And on startup, all alerts are shown. Instead of going to "ExpenseOverview" at first, it checks both my controllers and not just the one that is bound to "/ExpenseOverview".
What could be the cause of this?
EDIT: Knowing it's normal for Angular to access all controllers on startup, the main problem isn't fixed yet. This is explained in another thread on StackOverflow. I thought this had something to do with it, because I had no idea that it was normal behavior for Angular to do this.
I could say that this thread is closed, because I have an answer to my question now.
Angular does not access every controller on start up, however, ngRoute does. Any initialization code in a controller that has a corresponding route entry in $routeProvider, will run at initialization.
Here's an example of this at play: http://plnkr.co/edit/WsvbKhcR74yoX80bskdb?p=preview
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script data-require="ng-route#*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0-rc.3/angular-route.js"></script>
</head>
<body ng-controller="main">
<h1>Hello {{test}}!</h1>
<div ng-view="">Hello?</div>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/route1', {
controller: 'con1',
templateUrl: 'view1'
})
.when('/route2',
{
controller: 'con2',
templateUrl: 'view2'
})
.otherwise({ redirectTo: '/route1' });
});
app.controller('main', function($scope){
alert('1');
$scope.test = 'Yo.';
});
app.controller('con1', function($scope){
alert('2');
$scope.value = 'value1';
});
app.controller('con2', function($scope){
$scope.value = 'value2'
});
</script>
<script type="text/ng-template" id="view1">
View 1 {{value}}
</script>
<script type="text/ng-template" id="view2">
View 2 {{value}}
</script>
</body>
</html>
I'm having a problem in AngularJS routing and controllers. Here is the code:
Index.html
<!DOCTYPE html>
<html ng-app="contacts">
<head>
<script src="libs/angular.min%20(1).js"></script>
<script src="contacts.js"></script>
<script src="index.js"></script>
<title></title>
</head>
<body >
<div data-ng-view=""></div>
</body>
</html>
index.js
var myApp = angular.module('contacts', []);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', { controller: 'ContactsCtrl', templateUrl: '/views/show-contacts.html' })
//.when('/view2', { controller: 'MyCont', templateUrl: 'V2.htm' })
.otherwise({ redirectTo: '/' });
});
contacts.js
var myApp = angular.module('contacts', []);
myApp.controller('ContactsCtrl', function ($scope) {
$scope.name = "omar";
});
but I'm getting this error:
Argument 'ContactsCtrl' is not a function, got undefined
Any help?
Change your index.html like this;
<script src="index.js"></script>
<script src="contacts.js"></script>
And in your contact.js change
var myApp = angular.module('contacts', []); to
var myApp = angular.module('contacts');
Angular module with two arguments like angular.module('contacts', []); will create a new module, but angular module with single argument like angular.module('contacts'); will pick up the existing module. Here in this case 'contacts'
You are redefining your app in index.js, so the controller created in contacts.js is lost. Remove this line from index.js:
var myApp = angular.module('contacts', []);
I would suggest to create two different module names one in the index.js ( This would be the app name that you would refer in the html ng-app attribute) and other in contacts.js (The module name for the controllers). In the index.js create a dependecy to the contacts.js`. I was able to fix the problem by doing the below.
Updated contacts.js Here i updated the contacts to contactsController
var myApp = angular.module('contactsController', []);
myApp.controller('ContactsCtrl', function ($scope) {
$scope.name = "omar";
});
Updated index.js Here i added the contactsController as the dependency. I found it easier to name this as app.js. This way ng-app is always mapped to the module name in app.js.
var myApp = angular.module('contacts', [contactsController]);
myApp.config(function ($routeProvider) {
$routeProvider
.when('/', { controller: 'ContactsCtrl', templateUrl: '/views/show-contacts.html' })
//.when('/view2', { controller: 'MyCont', templateUrl: 'V2.htm' })
.otherwise({ redirectTo: '/' });
});