Dependencies in AngularJS App Level Module necessary or automatable? - angularjs

I started a project form the Angular Seed Project. I've done a few Angular projects before, but this is the first one I have setup from scratch. I don't remember having to add new modules to the "app level module" before. Seems like there is a way to automate this, but my Google-Fu is failing me.
Basically, I'm looking for a way to remove 'myApp.home' and such from app.js so that I don't have to always add new pages to the app.js. I know some modules will need to go there, but adding every page there seems like a pain. I already figured out how to automate adding the script references to index.html
//////////////////// APP.JS ////////////////////
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', [
'ngRoute',
'myApp.home'
])
.config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.otherwise({ redirectTo: '/home' });
}]);
//////////////////// HOME.JS ////////////////////
'use strict';
angular.module('myApp.home', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: '../app/home/home.html',
controller: 'HomeCtrl'
});
}])
.controller('HomeCtrl', [function () {
}]);
<!---------- INDEX.HTML ---------->
<html>
<head>
<title>My App</title>
</head>
<body>
<h1>My App</h1>
<div ng-view></div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="home/home.js"></script>
</body>
</html>
<!---------- HOME.HTML ---------->
<div>TEST</div>

if you will not create a new module for each new page, but use myApp module, then you do not need to add it as dependency to the myApp module. Each page will have its own JS file:
//////////////////// HOME.JS ////////////////////
'use strict';
angular.module('myApp')
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/home', {
templateUrl: '../app/home/home.html',
controller: 'HomeCtrl'
}
);
}])
.controller('HomeCtrl', [function () {
}
]);

Related

Unable to load controller within $routeProvider in AngularJS

This is my very first AngularJs app and created it after going through many examples on the web but I am doing something wrong here. It is highly likely because files are stored in dedicated folders. The HomeView.html template gets loaded fine but the controller doesn't. I mean I cannot get greetingMessage printed in the template. All I see is {{ greetingMessage }} instead of "Welcome!". What am I missing?
Error
Error: [$controller:ctrlreg] http://errors.angularjs.org/1.6.4/$controller/ctrlreg?p0=HomeController
App Structure
app
conponents
home
HomeView.html
HomeController.js
...
...
index.js
index.html
index.html
<body ng-app="myApp">
<h3>AngularJS</h3>
<hr />
<p>Home</p>
<div ng-view></div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
<script src="index.js"></script>
</body>
index.js
var module = angular.module('myApp', ['ngRoute']);
module.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'components/home/HomeView.html',
controller: 'HomeController'
// I tried -> controller: 'components/home/HomeController'
})
.otherwise({
redirectTo: '/'
});
});
HomeView.html
<div ng-controller="HomeController">
<h4>Home</h4>
<p>{{ greetingMessage }}</p>
</div>
HomeController.js
var module = angular.module('myApp', []);
module.controller('HomeController', [
'$scope',
function(
$scope
) {
$scope.greetingMessage = 'Welcome!';
}]);
The main reason is you haven't referred homeController.js on index.html, it should place right after index.js. This will not solve your issue. The other thing I'd like to mention is, you shouldn't be creating myApp module again while registering your controller with your myApp module. By declaring new module will flush out former registered component. So just use module getter like angular.module('myApp') and append further components to it.
<script src="components/home/HomeController.js">
Code
angular.module('myApp')
.controller('HomeController', [ '$scope',
function($scope) {
$scope.greetingMessage = 'Welcome!';
}
]);
You must be attach app file and next attache your controller file in your hoem page or master page.
This example helped you
Angular js routing

AngularJS controller not registered Error

I tried every solution on stackoverflow to make this error go but all to vain..
I am trying to use ngRoute to make SPA.
angular.js:14328 Error: [$controller:ctrlreg] The controller with the name 'loginCtrl' is not registered.
Here is my code
/* route file called controoler.js */
var app = angular.module('mainApp', ['ngRoute']).
config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'login/views/loginView.html',
controller: 'loginCtrl'
})
.when('/reward', {
templateUrl: 'rewardManagement/views/reward.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
// loginCtrl in login/controllers/loginCtrl.js
var app = angular.module('mainApp', []);
app.controller('loginCtrl', ['$scope', '$location', function($scope, $http, $location) {
$scope.changeView = function(view) {
$location.path(view); // path not hash
};
}]);
<!-- -------index.html--------- -->
<!DOCTYPE html>
<html lang="en" class="body-full-height" ng-app="mainApp">
<head>
<script src="/controller.js"></script>
<script src="../login/controllers/loginCtrl.js"></script>
</head>
<body>
<div ng-controller="loginCtrl"></div>
<ng-view></ng-view>
</body>
</html>
<!-- -------loginView.html--------- -->
<script src="../login/controllers/loginCtrl.js"></script>
<div ng-controller="loginCtrl">
<button ng-click="changeView('/reward')">Please Bypass this for now</button>
</div>
Please suggest a solution, in my project I will have many links which when clicked should change the ng-view according to the route. And I don't think putting all the .js scripts in index.html is a good idea, shouldn't each partial contain its own .js which also contains the controller?
Here is the working Plunkr
Just did some little changes in your controller code:
app.controller('loginCtrl', ['$scope', '$location', function($scope, $location) {
$scope.changeView = function(view) {
$location.path(view); // path not hash
};
}]);
Also you don't need to add the script again in your loginView.html

Using Angular route in webapi application

I'm not sure how can I implement proper Angular routing in web api application. I'm able to open the pages using this approach: http://localhost:52876/HTML/app/borrower.html
The Angular controller loads fine and all functionality is there from the angular side.
Now, I want to be able to open the views in a bit better view, using ng-route, so for example http://localhost:52876/HTML/app/borrower.html will become http://localhost:52876/borrower.
I included the ng-route.js file in the html files which I'm using in my angular app.
Also in app.js I have this:
'use strict';
var modules = [
'app.controllers',
'LoanAdminApplicationController',
'ngCookies',
'ngResource',
'ngSanitize',
'ngRoute',
'ui.router',
'LocalStorageModule',
'angular-loading-bar'
];
var app = angular.module('app', modules);
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when("/home", {
controller: "homeController",
templateUrl: "/app/views/home.html"
});
$routeProvider.when("/login", {
controller: "loginController",
templateUrl: "/HTML/login.html"
});
$routeProvider.when("/signup", {
controller: "signupController",
templateUrl: "/app/views/signup.html"
});
$routeProvider.when("/register", {
controller: "signupController",
templateUrl: "/app/views/register.html"
});
$routeProvider.when("/refresh", {
controller: "refreshController",
templateUrl: "/app/views/refresh.html"
});
$routeProvider.when("/tokens", {
controller: "tokensManagerController",
templateUrl: "/app/views/tokens.html"
});
$routeProvider.when("/borrower", {
controller: "borrowerController",
templateUrl: "/HTML/app/borrower.html"
});
$routeProvider.otherwise({ redirectTo: "/home" });
});
The html markup (I removed the content):
<!DOCTYPE html>
<html ng-app="app">
<head>
</head>
<body ng-controller="BorrowerQuickQuoteApplication">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="/assets/js/jquery.min.js"></script>
<script src="/assets/js/modernizr.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/assets/js/bootstrap.min.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-cookies.min.js"></script>
<script src="/Scripts/angular-resource.min.js"></script>
<script src="/Scripts/angular-sanitize.min.js"></script>
<script src="/Scripts/angular-route.min.js"></script>
<script src="/Scripts/angular-ui-router.min.js"></script>
<script src="/Angular/controllers.js"></script>
<script src="/Angular/LoanApplicationController.js"></script>
<script src="/Angular/services.js"></script>
<script src="/Scripts/angular-local-storage.min.js"></script>
<script src="/Scripts/loading-bar.min.js"></script>
<script src="/Angular/app.js"></script>
</body>
</html>
Any idea what I need to do in order to make this working?
Should I modify the RouteConfig.cs file or I need to do anything else as well?
You don't navigate with the file name as you are doing that's angular route job to do for example
$routeProvider.when("/borrower", {
controller: "borrowerController",
templateUrl: "/HTML/app/borrower.html"
});
when you go to localhost:8080/yourapp/borrower
and you need ng-view in your index.html
Like this
<div ng-view></div>
your pages will be shown here.
router will look that you are requesting for the borrower and it will take you to the /HTML/app/borrower.html
You are using html five mode that means you need server side routing to so it can fall to index.html every time so your url can be without hash.

AngularJS controller function not called

So I have my index page:
<!DOCTYPE html>
<html ng-app="application" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="app/app.js"></script>
</head>
<body>
<!-- Place where the page will be rendered at -->
<div ng-view>
</div>
</body>
</html>
The application looks like this:
var application = angular.module('application', ["ngRoute"]);
application.config(["$routeProvider", "$locationProvider",
function ($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
templateUrl: "app/ListContactsForm/lcTemplate.html",
controller: "HomeController"
})
.otherwise({
redirectTo: "/home"
});
//$locationProvider.html5Mode(true);
}]);
application.controller("HomeController",
["$scope", "$location", "DataService",
function ($scope, $location, DataService) {
alert("home hit!");
}]);
The lcTemplate.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>aaaa</title>
</head>
<body>
I'm here!!
</body>
</html>
The problem is that the lcTemplate is rendered, i get the "I'm here!!" message, but he HomeController function is never called. Why is that so?
The problem was in injecting the DataService which did not exist (I removed the service).
Error: [$injector:unpr] http://errors.angularjs.org/1.3.12/$injector/unpr?p0=DataServiceProvider%20%3C-%20DataService%20%3C-%20HomeController
Changes which needed to be done were all in the application code:
var application = angular.module('application', ["ngRoute"]);
application.config(["$routeProvider", "$locationProvider",
function ($routeProvider, $locationProvider) {
$routeProvider
.when("/home", {
templateUrl: "app/ListContactsForm/lcTemplate.html",
controller: "HomeController"
})
.otherwise({
redirectTo: "/home"
});
//$locationProvider.html5Mode(true);
}]);
application.controller("HomeController",
["$scope", "$location",
function ($scope, $location) {
alert("home hit!");
}]);
You have to remove the complete HTML definition from the template because the view is rendered inside
<div ng-view>
</div>
lcTemplate.html: should be like
<div>I'm here!!</div>
You have not declare "DataService". for example: I have my services in model_services.js
var services = angular.module('ModelServices');
services.factory('DataService', ['$resource', function($resource){
var DataService = $resource('/api/data/:id', {id: "#id" });
return DataService;
}]);
This method is for call to any consuming services. '/api/data/:id' is your API Rest path.
After that you have to add your module in your config application, for this example 'ModelServices'
var application = angular.module('application', ["ngRoute", "ModelServices"]);
Now you can call your "DataService" from the controller
application.controller("HomeController",
["$scope", "$location", "DataService",
function ($scope, $location, DataService) {
console.log("home hit!");
}]);
I have not idea if you can call "alert" from controller but I'm sure can you use console.log instead.
As you say #omegasbk "The problem was in injecting the DataService which did not exist (I removed the service)." if you have not declare your module that contain your "DataService" object in your application then you can not use this in your controller.

Angular: Routing while using Ui Bootstrap

I'm trying to build an application and am using bootstrap ui to use the accordion and the datepicker for example.
However, when I try to add routing via the ng-route module, the ui part stops working.
Without the routing part the definition of my ng-app looks as follows:
var myApp= angular.module('myApp', ['ui.bootstrap']);
In the angular tutorial they say to use the routing thing i have to put the ng-app definition like this:
var myApp= angular.module('myApp', [
'ngRoute',
'Controllers'
]);
So combined it should look like this:
var myApp = angular.module('myApp', [
'ngRoute',
'Controllers',
'ui.bootstrap'
]);
Or am I wrong? Because like this, it doesn't work.
The index.html file looks like this:
!DOCTYPE html>
<html ng-app='myApp'>
<head>
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers2.js"></script>
<script src="ui-bootstrap-tpls-0.9.0.js"></script>
<link rel="stylesheet" href="css/bootstrap-3.1.1-dist/css/bootstrap.css">
<link rel="stylesheet" href="css/app.css">>
</head>
<body>
<div ng-view></div>
</body>
</html>
controllers2.js doesn't define any controllers yet:
var Controllers= angular.module('Controllers', []);
Controllers.controller('firstCtrl', ['$scope', '$http','$routeParams',
function ($scope, $http) {
}]);
Controllers.controller('secondCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
}]);
app.js handles the routing part:
var myApp = angular.module('myApp', [
'ngRoute',
'Controllers',
'ui.bootstrap'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/first', {
templateUrl: 'first.html',
controller: 'firstCtrl'
}).
when('/second', {
templateUrl: 'second.html',
controller: 'secondCtrl'
}).
otherwise({
redirectTo: '/first'
});
}]);
first.html and second.html don't do much either:
first.html:
<h1>first</h1>
second
<accordion close-others="oneAtATime">
<accordion-group heading="Heading 1" is-open="true">
TSome Content
</accordion-group>
<accordion-group heading="Heading 2">
Some Content
</accordion-group>
</accordion>
second.html:
<h1>second</h1>
first
The first.html should look like this, with working bootstrap:
Any time you call angular.module('myApp', []) with that second parameter, you're creating a module.
angular.module('myApp', []) //<-- will create a new module called myApp
angular.module('myApp') //<-- will look for an existing instance of a myApp module.
If you're creating an instance more than once, with the same name, the first instance will be overwritten by the second one.
Do you have a 'controllers' module defined before you try to load your app ?
If not remove it from the dependencies:
var myApp = angular.module('myApp', [
'ngRoute',
'ui.bootstrap'
]);
Is Controllers misspelled? One appears to be in lower case, 'controllers' and the other in Sentence case 'Controllers'.
Regardless, Try bring up the debugger on your browser (F12 on a window system) and see if any error messages are being written to the console window when you refresh the page(F5 or the browser refresh button). I find that when my pages are acting funny the console usually provides me a hint.
In my case deleting ngAnimate fixed problems with ui.bootstrap.

Resources