Controllers in seperate files in Ionic and include order - javascript

I started to write an Ionic application and started to write my views and controllers. I want to use a tab-layout.
For clarity i want to seperate my controllers in different files.
My controllers-Folder:
controller.js
main.js
tabs.js
controller.js contains:
angular.module('myApp.controllers', []);
main.js contains:
angular.module('myApp.controllers', ['myApp.services','ionic'])
.controller('MainCtrl', function ($scope) {
$scope.name = "Test";
});
tabs.js contains:
angular.module('myApp.controllers', ['myApp.services','ionic'])
.controller('TabsCtrl', function ($scope) {
});
In the app.js i specify my routings:
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'app/templates/tabs.html',
controller: 'TabsCtrl'
})
.state('tab.main', {
url: '/main',
views: {
'tab-main': {
templateUrl: 'app/templates/main.html',
controller: 'MainCtrl'
}
}
})
And finally in my index.html i include all used files in the header:
<script src="app/app.js"></script>
<!-- Controller-Definition -->
<script src="app/controller/controller.js"></script>
<script src="app/controller/tabs.js"></script>
<script src="app/controller/main.js"></script>
My problem is that in the browser i get the error:
Argument 'TabsCtrl' is not a function, got undefined
and i don't know why its not working!
when i change the order of the tabs.js und main.js in the index.html file
i get:
Argument 'MainCtrl' is not a function, got undefined
Could someone give me help on this problem? it's probably is something small and simple but i don't get it :-)

You overwrite 'myApp.controllers' module in each file. Try this:
controller.js:
angular.module('myApp.controllers', ['myApp.services','ionic']);
main.js:
angular.module('myApp.controllers')
.controller('MainCtrl', function ($scope) {
$scope.name = "Test";
});
tabs.js
angular.module('myApp.controllers')
.controller('TabsCtrl', function ($scope) {
});

Related

AngularJS ui-router not rendering view

I've been struggling with getting my AngularJS app to display a view based on a template.
The issue: ui-router seems to be correctly "routing" all the files, because the template file (landing.html) is being delivered to the console as an object (see console.log(result) in main.js below). Nevertheless, the template file is not being displayed in the app where <div ui-view></div> is supposed to be.
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
##include('partials/head.html')
<body>
##include('partials/header.html')
<div ui-view></div>
##include('partials/footer.html')
</body>
</html>
main.js:
angular.module('myApp', [
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('landing', {
url: '/',
controller: 'LandingCtrl as landing',
templateUrl: 'templates/landing.html'
});
$urlRouterProvider.otherwise('/landing');
}])
.run(['$http', '$templateCache', function($http, $templateCache) {
$http.get('templates/landing.html', {
cache: $templateCache
}).then(function(result) {
console.log(result);
});
}]);
My template file landing.html:
<main class="content">
##include('partials/search.html')
<h2>Show me the contents of landing.html!</h2>
</main>
I'm using grunt and made sure to have it both watch and copy the /templates into /dist. Overall the Angular app is behaving correctly (no ng errors in the console).
Also, if instead of specifying a template file (templateURL), I simply use template: <h2>Show me the contents of landing.html!</h2> in main.js then this is rendered in the view. There's something preventing a file from being rendered.
Question: Given ui-router is correctly finding and routing all files, does anyone have an idea as to why the app is simply not displaying the template file?
Edit Here is LandingCtrl.js:
(function() {
function LandingCtrl($scope, $location, $anchorScroll) {
$scope.goTo = function(id) {
$location.hash(id);
console.log($location.hash());
$anchorScroll();
};
}
angular
.module('myApp')
.controller('LandingCtrl', ['$scope', '$location', '$anchorScroll', LandingCtrl]);
})();
in your main.js file change the url of Landing State as below:
angular.module('myApp', [
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('landing', {
url: '/landing',
controller: 'LandingCtrl as landing',
templateUrl: 'templates/landing.html'
});
$urlRouterProvider.otherwise('/landing');
}])
.run(['$http', '$templateCache', function($http, $templateCache) {
$http.get('templates/landing.html', {
cache: $templateCache
}).then(function(result) {
console.log(result);
});
}]);

Controller not registering when using nested view

My app was working fine until I changed routing from ngRoute to ui-Router so I could use power of views within views. Now the controllers of the views are not being registered. My folder structure is like this:
index.html
<html ng-app="myApp">
<body>
<div ui-view></div>
<script src="js/app.module.js"></script>
<script src="js/components/foodCategories/foodCategoriesController.js"></script>
<!-- other controllers -->
<script src="js/app.route.js"></script>
</body>
</html>
app.module.js
angular.module('myApp', ['ui.router'])
app.route.js
angular.module('myApp')
.config(['$stateProvider', '$urlRouterProvider', statesManager])
function statesManager($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/')
$stateProvider
.state('profile', {
url: '/profile',
views: {
'': {
templateUrl: '/js/components/profile.html'
},
'foodCategories#profile': {
templateUrl: '/js/components/foodCategories/foodCategories.html',
controller: 'FoodCategoriesController'
}
}
})
}
profile.html
<div ui-view="foodCategories"></div>
foodCategories.html
<div id="foodcategories" ng-controller="FoodCategoriesController">
<!-- other stuffs -->
foodCategoriesController.js
(function () {
angular
.module('myApp')
.controller('FoodCategoriesController', controlFunc)
function controlFunc ($scope) {
....my stuffs...
}
})()
I am not sure why the controller is not being registered. The controller file is loaded when I check Networks in Developers Tools but I get Error: [$controller:ctrlreg] on all controllers.
Thank You :)
You dont need ng-controller="FoodCategoriesController". Remove it.

AngularJS routing without webserver?

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']);

Error: $injector:modulerr Module Error, property 'when' of undefined Angular

I have been researching and trying to figure out this error for 2days now and Still no luck.
To begin I new to angular, and I have following this tutorial : http://jphoward.wordpress.com/2013/01/04/end-to-end-web-app-in-under-an-hour/
Every was going well until my grid was not filling with data. So I decided to make minor changes to code and now I have ran into this error.
in my js file:
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config([function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
MyApp.factory('Myapp', function ($resource) {
return $resource('/Myapp/:id', { id: '#id' }, { update: {
method: 'PUT' } });
});
MyApp.controller('ListCtrl', ['$scope', 'ds72', function ($scope, Myapp) {
$scope.todos = Myapp.query();
}]);
can some one please explain to me what i am doing wrong?
PS: These are all my Scripts
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/angular.js"></script>
<script src="/Scripts/angular-resource.min.js"> </script>
<script src="/Scripts/angular-route.min.js"></script>
try something like that
var MyApp = angular.module("Myapp", ["ngResource", "ngRoute"]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'list.html', controller: 'ListCtrl' }).
otherwise({ redirectTo: '/' });
}]);
you must add the name of the provider to inject when you use the array declaration
.config(['$routeProvider'/*must be the exact name*/, function(route/*get the $routeProvider value*/) {}])
//equivalent as
.config(function($routeProvider) {})

Argument 'ContactsCtrl' is not a function, got undefined

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: '/' });
});

Categories

Resources