I am using Angularjs for my application.I am having one common page which has header and footer which i am making common for all pages.Thats y i am placing it in one common html.Only contents code i am placing in other html pages.
As i am using one common page i am loading all controllers and all Services that i am using in the application.
Here is my commonpage.html
<!DOCTYPE html>
<html lang="en" data-ng-app="adminApp">
<head>
</head>
<body>
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="resources/angular/controller/admin/AdminExamController.js">
</script>
<script src="resources/angular/service/admin/AdminExamService.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
The doubt i am having is,is it necessary to place all controllers and services like i am doing because i am facing performance issue even though i am connected to strong internet it loads very slow.As i am placing all in one page it is loading all controllers and services everytime.If i place controllers in their respective html then i am getting error like ExamController.js or any .js Controller not defined.Is there any other way that i can load all controllers and services so that i can increase the performance of the application?
I think this is what your looking for
app.js
/* Module Creation */
var app = angular.module ('adminApp', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript(name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/view2', {
templateUrl: 'view2.html',
resolve: loader(['Controller2'])
})
.when('/bar',{
templateUrl: 'view1.html',
resolve: loader(['Controller1'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<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>
</head>
<body ng-app="adminApp">
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="app.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
Controller 1.js
(function(val){
'use strict';
angular.module('Controller1App', [])
.controller('Controller1', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Controller 2.js
(function(val){
'use strict';
angular.module('Controller2App', [])
.controller('Controller2', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Refer https://plnkr.co/edit/cgkgG5PCwJBVOhQ1KDW2?p=preview
Related
Below is my index.html page which has two buttons which links to 2 different views which i intend to show using angular routing.
Below is my
HTML
<!DOCTYPE html>
<html>
<head>
<title>PR_APP</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<script src="js/main.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update()">Update Details</button>
</div>
<div ng-view>
</div>
</body>
Below is my main.js file which houses both above mentioned controller and logic for angular routing.
main.js
var app = angular.module('new_pr_app', ['ngRoute']);
app.config('$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
});
app.controller("view_controller",function($scope, $location, http_factory){
$scope.view = function(){
$location.path("/view");
}
$scope.result =[];
http_factory.get_request().then(function(response){
$scope.result = response.data;
});
});
app.controller("update_controller",function($scope, $location, http_factory){
$scope.update_details = function(){
$location.path("/update");
}
$scope.names = [];
http_factory.get_request().then(function(response){
$scope.names = response.data;
});
});
I have another file called services.js which has a service factory to get details from a json file using an http get.
My only problem seems to be in the above main.js which gives the error below everytime index.html loads
angular.js:88 Uncaught Error: [$injector:modulerr]
Your config is wrong. You pass in a string as the first (and second argument), while the .config(..) function, expects a function to be passed in (or an array).
In your code, you simply forgot to wrap the arguments in an array. Here's how it should look:
app.config(['$routeProvider','$locationProvider',
function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
templateUrl:"update.html",
controller: "update_controller"
})
.when("/view",
{
templateUrl: "view.html",
controller: "view_controller"
});
}]);
Note the [ and ] wrapping the content
You can check with below code.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-route.js"></script>
<body ng-app="new_pr_app">
<h2>Please select an option</h2><br>
<div ng-controller="view_controller">
<button id="view_details" ng-click="view()">View Details</button>
</div>
<div ng-controller="update_controller">
<button id="update_details" ng-click="update_details()">Update Details</button>
</div>
<div ng-view>
</div>
<script>
var app = angular.module('new_pr_app', ['ngRoute']);
app.config(['$routeProvider','$locationProvider', function($routeProvider,$locationProvider){
$routeProvider.when("/update",
{
template:"update template"
// controller: "update_controller"
})
.when("/view",
{
template: "view template"
// controller: "view_controller"
});
}]);
app.controller("view_controller",function($scope, $location){
$scope.view = function(){
$location.path("/view");
}
});
app.controller("update_controller",function($scope, $location){
$scope.update_details = function(){
$location.path("/update");
}
});
</script>
</body>
</html>
I've a very simple app with no code in it yet. I've removed it to check for this error that I am getting - "angular.js:13708 Error: [ng:areq] Argument 'ClientFileConfigController' is not a function, got undefined"
I've followed the similar patter in my angularjs app (1.5.3) and it works fine. This code is using angularjs (1.5.7) and the only difference is I used bower to individually chose my packages, rather than using nuget.
I am unable to decode this error :-(
app.js
(function () {
var app = angular.module('ConfigApp', ['ngRoute', 'ngAnimate', 'TreeWidget']);
app.config(['$routeProvider', function ($routeProvider) {
var viewBase = '/app/ConfigApp/views/';
$routeProvider
.when('/clients', {
controller: 'ClientFileConfigController',
templateUrl: viewBase + 'clients.html',
controllerAs: 'vm'
})
//.when('/clients/:clientId/:fileId', {
// controller: 'clientfileEditController',
// templateUrl: viewBase + 'edit.html',
// controllerAs: 'vm'
//})
.otherwise({ redirectTo: '/clients' });
}]);
}());
clientfileConfigController.js
(function(){
var injectParams = ['$scope'];
var ClientFileConfigController = function ($scope) {
}
ClientFileConfigController.$inject = injectParams;
angular.module('ConfigApp').controller('ClientFileConfigController', ClientFileConfigController)
}());
index.html
<html ng-app="ConfigApp">
<head>
<title>Client File Angular Tree Widget</title>
<meta charset="utf-8" />
</head>
<body ng-cloak>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Clients</li>
</ul>
</div>
</div>
</nav>
.top-buffer { margin-top:20px; }
<div class="slide-animation-container">
<div ng-view id="ng-view" class="slide-animation"></div>
</div>
</body>
</html>
clients.html
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<h1>Hello World</h1>
<!--<tree nodes='treeNodes'>-->
</body>
</html>
Error Image
Change your IIFE to this structure:
(function (){
//your code here
})()
and include your controller in the script
You get this error on two scenarios:
Controller not included in script. (undefined)
Injector dependency couldn't be resolved.
I would say that you need to include the js files in your index html page. Angular is looking for your controller but there is no file specified that contains the code for it
Still learning angular, I would like to tap on an item from a list and show alert with the name of the item that was tapped.
In mainMenu.html ng-click is registered with the list element ng-click="mainMenuSelection(item.name), but the alert(name) is not being called in controllers.js
What am I doing wrong? Thanks
I also noticed the Google Chrome Sources does not show the views folder which contains mainMenu.html as per the second image.
//---app.js-----------------------------------------------
(function () {
'use strict';
angular
.module('angApp', ['ngRoute'])
.config(['$routeProvider', routeProvider]);
})();
function routeProvider ($routeProvider) {
$routeProvider.when('/list', {
templateUrl: 'views/mainMenu.html',
controller: 'MainMenuCtrl'
}).otherwise({ //home page
redirectTo: '/list'
});
}
angular.element(document).ready(function () {
angular.bootstrap(document, ['angApp']);
});
//---controllers.js-----------------------------------------------
angular
.module('angApp')
.controller('MainMenuCtrl', ['$scope', '$http', MainMenuCtrl]);
function MainMenuCtrl ($scope, $http) {
$http.get('js/mainMenu.json').then(
function (response) {
$scope.menuItems = response.data;
},
function (error) {
alert("http error");
}
)
$scope.mainMenuSelection = function(item) {
alert(item);
}
}
//---headerCtrl.js-----------------------------------------------
angular
.module('angApp')
.controller('HeaderCtrl', ['$scope', HeaderCtrl]);
function HeaderCtrl() {
var vm = this;
vm.title = "Tap left menu \u2630";
vm.headerTitle = setHeaderTitle;
function setHeaderTitle(title) {
vm.title = title;
}
}
//---index.html-----------------------------------------------
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/index.css">
<base href="http://localhost:63342/an1/">
<script src="angular.js"></script>
<script src="angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/controllers.js"></script>
<script src="js/controllers/headerCtrl.js"></script>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<main ng-view></main>
</body>
</html>
//---mainMenu.html-----------------------------------------------
<section class="mainMenu">
<ul>
<li ng-repeat="item in menuItems" ng-click="mainMenuSelection(item.name)">
<image src="images/{{item.image}}.png"></image>
{{item.name}}
</li>
</ul>
</section>
I created a fiddle with a working example close to what you want.
Obviously, I have a much pared down version for the sake of brevity.
http://jsfiddle.net/frishi/U3pVM/21624/
(function () {
'use strict';
angular
.module('angApp', [])
.controller("MainMenuCtrl", MainMenuCtrl)
})();
function MainMenuCtrl ($scope, $http) {
$scope.menuItems = [{
name:"Tom"},
{name: "Harry"},
{name: "Wiley"}
]
$scope.mainMenuSelection = function(item) {
alert(item);
}
}
Markup:
<div ng-app="angApp">
<section class="mainMenu" ng-controller="MainMenuCtrl">
<ul>
<li ng-repeat="item in menuItems" ng-click="mainMenuSelection(item.name)">
<image src="images/{{item.image}}.png" />
{{item.name}}
</li>
</ul>
</section>
</div>
I used a hard-coded JSON array of objects.
I also don't bootstrap the app the way you do.
There is too little information that your question provides, as to what could be the fault. Follow the example as specified in the fiddle, and if that doesn't work, reply with more details.
Here is my version in Plunker. I was trying to follow your file structure.
Make sure that <body ng-app="angApp"> is there, thats only one thing that I've added (I now it looks too trivial...)
EDIT: adding Git repo
Git repo with working code => clone => cd to directory => npm instal = npm start => files will be served on port:63342 (serving file using node sever in order to replicate environment where issue is happening)
var routerApp = angular.module('routerApp', ['ui.router','ngResource']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// HOME STATES AND NESTED VIEWS
.state('partyDetail', {
url: '/party/:partyID',
templateUrl: 'hello.html',
controller: function($scope, $stateParams, UserFactory) {
$scope.id = $stateParams.partyID;
console.log($stateParams.partyID);
UserFactory.get({}, function (userFactory){
$scope.userdata = userFactory.user;
});
}
});
});
routerApp.controller('chappy',[function(){
var thisOne=this;
thisOne.note=[
{id:1,Name:'emp.json',Status:false},
{id:2,Name:'1',Status:true},
{id:3, Name:'2',Status:false}
];
console.log("I'm in controller");
}]);
routerApp.factory('UserFactory', function ($resource,$stateParams) {
console.log($stateParams.partyID);
return $resource(':Id',{Id: $stateParams.partyID }, {
query: {
method: 'GET',
params: {},
isArray: true
}
})
});
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS (load bootstrap) -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- JS (load angular, ui-router, and our custom js file) -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js" ></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular-resource.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app to our site -->
<body ng-app="routerApp">
<!-- NAVIGATION -->
<nav class="navbar navbar-inverse" role="navigation" ng-controller="chappy as chappu">
<ul class="nav navbar-nav" ng-repeat="result in chappu.note">
<li><a ui-sref="partyDetail({ partyID: result.Name })" ><span ng-bind="result.Name"></span></a></li>
</ul>
</nav>
<!-- MAIN CONTENT -->
<div class="container">
<!-- THIS IS WHERE WE WILL INJECT OUR CONTENT ============================== -->
<div ui-view></div>
</div>
</body>
</html>
<!--partial html which is needed to be included in the ui-view-->
<!--hello.html-->
<div>
<p > what were you saying <span ng-bind="id"></span></p>
<p ng-repeat="result in userdata">
<span ng-bind="result.subject"></span>
</p>
</div>
I have created Here a DemoApp in which I have dynamically Created The URi according to the data coming from the different Controller
The Programs seems to work fine at the first glance but it has a problem that the $stateparams even After changes but in the URi it remains the same
The issue here is that maybe my not services is getting called again
but I am not been able to encounter this bug
var routerApp = angular.module('routerApp', ['ui.router','ngResource']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// HOME STATES AND NESTED VIEWS
.state('partyDetail', {
url: '/party/:partyID',
The Console output clearly indicates that the Uri is same as it fetch the data for the first time
Clearly, either factory is not getting called again or $stateparams is not changing
help is appreciated
I had done some debugging of the code and I have find out since I was directly injecting the $stateparams in the factory that's why it is taking the first value it has attained
to sort it out I have included the id:$stateparams in the get request in the controller and it seemed to work
controller: function($scope, $stateParams, UserFactory) {
$scope.id = $stateParams.partyID;
UserFactory.get({'Id': $stateParams.partyID}, function (userFactory){
$scope.userdata = userFactory.user;
});
}
that's It , It will work like whammy
Im not sure where to place the partials folder holding the html views! I have placed it at the app root folder, in views and in public. Also tried removing the first trailing slash of the templateUrl but nothing. I also have tried(as view loading container):
<div ng-view></div>
<ng-view></ng-view>
<div data-ng-view></div>
<div ng-view=""></div>
<div ng-view="demoApp"></div>
This is just a learning example holding a module with 2 controllers and 2 views.
Here is the SPA(this page renders as rout '/' of a dancer(perl) project):
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<title><% title %></title>
<link rel="stylesheet" href="/customised_bootstrap/css/bootstrap.css">
<script src="/bower_components/underscore/underscore.js"></script>
<script src="/bower_components/backbone/backbone.js"></script>
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-resource/angular-resource.js"></script>
<script src="/bower_components/angular-route/angular-route.js"></script>
<script src="/bower_components/ng-tasty/ng-tasty-tpls.js"></script>
<script>
//define a module
var demoApp = angular.module('demoApp', ['ngRoute']);
//define routes for our module(each route will have its set of views and controllers)
demoApp.config =(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'simpleController1',
templateUrl: '/partials/testAlexView1.html'
})
.when('/testAlexView1',
{
controller: 'simpleController2',
templateUrl: '/partials/testAlexView1.html'
})
.when('/testAlexView2',
{
controller: 'simpleController2',
templateUrl: '/partials/testAlexView2.html'
})
.otherwise({redirectTo: '/partials/testAlexView1.html'});
});
//define a controller within our module 'demoApp'
demoApp.controller('simpleController1', function ($scope) {
$scope.customers = [
{name:'Boris', age:'18'},
{name:'Claudia', age:'28'},
{name:'Carlos', age:'39'},
{name:'Ben', age:'25'}
];
//var stuff ={};
});
demoApp.controller('simpleController2', function ($scope) {
$scope.customers = [
{name:'Alex', age:'18'},
{name:'Albert', age:'28'},
{name:'Anthony', age:'39'},
{name:'Loren', age:'25'}
];
});
</script>
</head>
<body>
<div>
<p>Main page of SPA test</p>
<div ng-view></div>
</div>
</body>
</html>
Here are the two identical views:
testAlexView1.html(testAlexView2.html is the same):
<div>
<input type="text" data-ng-model="name" /> {{ name }}
<br />
<ul>
<li data-ng-repeat="customer in customers | filter:name | orderBy:'age'">
{{customer.name}} - {{customer.age}}
</li>
</ul>
</div>
In the browser inspector, within the div where the view should load, all that appears is(both at root or root#/view.html):
<!-- ngView: -->
Batarang dosn't detect scopes nor modules neither. Thanks for any help!
There appears to be a typo in your config here:
demoApp.config =(function ($routeProvider) {
Instead try:
demoApp.config(function ($routeProvider) {