How to move controller configuration into its own file? - javascript

I have the following angular configuration in the file index.js:
angular.module('ionicApp', ['ionic'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('entry', {
url: '/entry',
templateUrl: 'app/views/entry/entry.html',
controller: 'EntryPageController'
})
$urlRouterProvider.otherwise('/entry');
}])
.controller('EntryPageController', ['$scope', '$state', function ($scope, $state) {
$scope.navTitle = 'Entry Page';
$scope.signIn = function () {
$state.go('main.home');
}
}])
I'm trying to move the controller definition (which works in the example above) into its own file, as follows:
// file name entry-ctrl.js
(function () {
'use strict';
angular.module('ionicApp', ['ionic'])
.controller('EntryPageController', ['$scope', '$state', EntryPageController]);
function EntryPageController($scope, $state) {
$scope.navTitle = 'Entry Page';
$scope.signIn = function () {
$state.go('main.home');
}
}
})
();
In index.html I've referenced the file as
<script src="app/views/entry/entry-ctrl.js"></script>
Unfortunately, I can't get the application to behave correctly. When I use the original code, the page appears as I expect. But when I use the code in the entry-ctrl.js file, nothing appears.
Is there something else I need to do to use the code in the entry-ctrl.js file?
For the record, this is my entry.html:
<ion-view title="{{navTitle}}" class="bubble-background">
<ion-content has-header="true" padding="true">
<h1>I'm working!</h1>
<a class="button button-positive" ng-click="signIn()" ui-sref="main.home">Sign In</a>
</ion-content>
</ion-view>

It's seems that you declared your angular app twice, once in index.js and in entry-ctrl.js.
I would change it to this:
index.js
angular.module('ionicApp', ['ionic'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('entry', {
url: '/entry',
templateUrl: 'app/views/entry/entry.html',
controller: 'EntryPageController'
})
$urlRouterProvider.otherwise('/entry');
}])
entry-ctrl.js
(function () {
'use strict';
angular.module('ionicApp')
.controller('EntryPageController', ['$scope', '$state', EntryPageController]);
function EntryPageController($scope, $state) {
$scope.navTitle = 'Entry Page';
$scope.signIn = function () {
$state.go('main.home');
}
}
})();
in angular, you declare your app with an array of dependencies:
angular.module('ionicApp', ['ionic'])
and you reference it only by name:
angular.module('ionicApp')

Would it be possible that your Controller definition has to be above your module definition ?
(function () {
'use strict';
// First, define your Controller
function EntryPageController($scope, $state) {
$scope.navTitle = 'Entry Page';
$scope.signIn = function () {
$state.go('main.home');
}
}
// Then call it in your module
angular.module('ionicApp', ['ionic'])
.controller('EntryPageController', ['$scope', '$state', EntryPageController]);
})(this);

Related

AngularJS Routing to different page with different controller

I have two HTML pages. One is the exam.html and other is result.html. On certain condition in the controller ExamCtrl of exam.html, I route to result.html using $location.path. But however, on the result page, the controller ResultCtrl doesn't seem to load though I have added it in the config file.
angular config file:
angular.module('exam').config(['$stateProvider',
function ($stateProvider) {
// Exam state routing
$stateProvider
.state('exam', {
abstract: true,
url: '/exam',
template: '<ui-view/>'
})
.state('exam.list', {
url: '',
templateUrl: 'modules/exam/client/views/exam.client.view.html',
controller: 'ExamCtrl'
})
.state('/result', {
url: '/result',
templateUrl: 'modules/exam/client/views/exam-result.client.view.html',
contoller: 'ResultCtrl'
});
}
]);
ExamCtrl:
angular
.module('exam')
.controller('ExamCtrl', ['$scope', '$stateParams', '$location', 'Authentication', '$http',
function ($scope, $stateParams, $location, Authentication, $http) {
$scope.submitAnswer = function (selected) {
//some code
if (qtnCounter > 5) {
// loads the result page.
$location.path('/result');
} else {
$scope.getQues();
}
};
}
]);
ResultCtrl:
angular
.module('exam')
.controller('ResultCtrl', ['$scope', '$stateParams', '$location', 'Authentication', '$http',
function ($scope, $stateParams, $location, Authentication, $http) {
console.log('ResultCtrl');
}
]);
result.html:
<body ng-controller="ResultCtrl">
<h1>Result page!</h1>
</body>
Insted of using $location use the $state to change to a given state in your app.
Inject the $state in the controller and then call the transitionTo() which will load the view and setup the controller
angular
.module('exam')
.controller('ExamCtrl', ['$scope', '$state', 'Authentication', '$http',
function ($scope, $state, Authentication, $http) {
$scope.submitAnswer = function (selected) {
//some code
if (qtnCounter > 5) {
// loads the result page.
$state.transitionTo('/result');
} else {
$scope.getQues();
}
};
}
]);

AngularJS: homeController is not showing up

This is app.states.js:
angular.module('fuelComparatorApp', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/404');
$urlRouterProvider.when('', '/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/components/home/views/home.view.html',
controller: "homeController",
controllerAs: 'ctrl'
})
.state('404', {
url: '/404',
templateUrl: 'app/shared/404.html'
});
}]);
And this is home.services.js:
(function () {
'use strict';
angular.module('fuelComparatorApp.homeServices', []).service('sayHelloService', sayHelloService);
sayHelloService.$inject = ['$http', '$q'];
function sayHelloService() {
function sayHi() {
console.log("hi from home service");
}
}
})();
home.controller.js
(function () {
'use strict';
angular.module('fuelComparatorApp').controller('homeController', homeController);
homeController.$inject = ["$scope", "$http", "$window", "$q", "sayHelloService"];
function homeController($scope, $http, $window, $q, sayHelloService) {
const vm = this;
vm.fuelComparatorService = sayHelloService;
sayHelloService;
return vm;
}
})();
Inside the index.html there is the usual ng-app="fuelComparatorApp" and home.view.html which utilises ng-controller="homeController" directive.
There are no errors, just the index.html doesn't show a anything from home.view.html as if I missed something somewhere.
Turned out this was missing from the index.html
<div ui-view></div>
This is specific to ui-router.

Use a service in Angular

I got some problem when I'm trying to use an Angular service in the controlleur of my application.
When I'm trying to use function of my service in my controlleur, my console throw me an error :/
var app = angular.module('app', ['ngRoute'])
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/login', {
controlleur: 'login',
templateUrl: 'modules/login/login.html'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.service('coreServices', [function () {
this.helloConsole = function () {
console.log("console services");
};
}]);
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, coreServices) {
var vm = this;
vm.helloConsole = coreServices.helloConsole;
vm.helloConsole();
}
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
I link you this fiddle to show you how I do: https://jsfiddle.net/h8yaxLap/2/
The error throwed is:
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
Well in your example angular will map $location to coreService in the injected parameters in the function. So I would go for
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, $location, coreServices)
Change service function to return object
app.service('coreServices', function () {
return {
helloConsole: function () {
console.log("console services");
}
};
});
You missed $location parameter for the controller
function LoginController($scope, $http, $rootScope,$location, coreServices)

Putting app, controllers & services in separate files

I'm trying to move angular code into separate files before the project grows too big.
I tried moving the app, controllers and services into separate files but the errors stopped referencing points in the code (or they were too generic).
I have decided to put the file contents in on big <script> tag so I can work through the errors and get it working. Unfortunately I have come across this (Failed to instantiate module protonApp due to...) and don't know how to track the problem down (I'm new to angular)
The
(function () {
'use strict';
...
}());
I have round the code is because the (little) research I have done says you should have your code between these when they are in separate files.
(function () {
'use strict';
var app = angular.module('protonApp',['ui.router','protonAppControllers','protonAppServices']);
app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
...
}]);
app.value('debug',true);
app.run(function($rootScope,$state,$http,debug,LeftMenuService) {
...
});
}());
(function () {
'use strict';
angular.module('protonAppControllers', ['$scope','$http','LeftMenuService']);
}());
(function () {
'use strict';
angular.module('protonAppServices', ['$rootScope','$http']);
}());
(function () {
'use strict';
angular.module('protonAppControllers').controller('loginController',['$scope','$http','$state',function($scope,$http,$state){
...
}]);
}());
(function () {
angular.module('protonAppControllers').controller('surveyListController',['$scope','$http','LeftMenuService',function($scope,$http,LeftMenuService){
...
}]);
}());
(function () {
'use strict';
angular.module('protonAppControllers').controller('surveyHelpController',['$scope','$http','LeftMenuService',function($scope,$http,LeftMenuService){
...
}]);
}());
(function () {
'use strict';
angular.module('protonAppServices').service('LeftMenuService', function($http,$rootScope){
...
});
}());
EDIT
Further digging reveals I can not access $rootScope or $scope inside any of my controller files
In your module injection you don't have to add $scope and $http :
angular.module('protonAppServices', []);
Inject these in the controller but not in the module declaration
You dont need to inject anything while declaring a module, you could use them in you controller as mentioned #ThibauDL
I usually prefer declaring the modules just above the angular app declaration.
I have modified your a code in plnkr which should give you an idea as to how the code must be organized.
(function() {
'use strict';
angular.module('protonAppControllers', []);
angular.module('protonAppServices', []);
var app = angular.module('protonApp', ['ui.router', 'protonAppControllers', 'protonAppServices']);
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
//...
}
]);
app.value('debug', true);
app.run(function($rootScope, $state, $http, debug, LeftMenuService) {
//...
});
}());
(function() {
'use strict';
angular.module('protonAppServices').service('LeftMenuService', function($http, $rootScope) {
//...
});
}());
(function() {
'use strict';
angular.module('protonAppControllers').controller('loginController', ['$scope', '$http', '$state',
function($scope, $http, $state) {
$scope.login = "Hi Please login!";
// ...
}
]);
}());
(function() {
angular.module('protonAppControllers').controller('surveyListController', ['$scope', '$http', 'LeftMenuService',
function($scope, $http, LeftMenuService) {
//...
}
]);
}());
(function() {
'use strict';
angular.module('protonAppControllers').controller('surveyHelpController', ['$scope', '$http', 'LeftMenuService',
function($scope, $http, LeftMenuService) {
$scope.test = "Hxxxxi";
//...
}
]);
}());
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="protonApp">
<div ng-controller="loginController">
<input type="text" ng-model='login' />
</div>
</body>
Also you could now place them in separate files as you wanted.
Hope that helps.

Angularjs Restful using ngResource not working

I am trying to expose restful web service using angularjs ngResource using java as my backend everything seems to be correct but don't know What is wrong with my code
nothing gets displayed in browser help me with this
service.js
'use strict';
var employeeServices = angular.module('myApp.services',['ngResource']);
employeeServices.factory('Employees',['$resource',function ($resource){
return $resource('my service link', {},{
query:{method:'GET',isArray:true}
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers',[]).
controller('Myctrl1',['$scope','Employees',function ($scope ,Employees){
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2',[function (){
}]);
app.js
'use strict';
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1',{templateUrl:'partials/partials.html',controller:'Myctrl1'});
$routeProvider.when('/view2',{templateUrl:'partials/partials1.html',controller:'Myctrl2'});
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
If you want to use service of one module in another module you have to inject it.
service.js
'use strict';
var employeeServices = angular.module('myApp.services', ['ngResource']);
employeeServices.factory('Employees', ['$resource', function ($resource) {
return $resource('my service link', {}, {
query: { method: 'GET', isArray: true }
});
}]);
Controller.js
'use strict';
angular.module('myApp.controllers', ['myApp.services']).
controller('Myctrl1', ['$scope', 'Employees', function ($scope, Employees) {
$scope.allemployees = Employees.query();
}]).
controller('Myctrl2', [function () {
}]);
app.js
'use strict';`enter code here`
angular.module("myApp", [
'ngRoute',
'myApp.controllers',
'myApp.services'
]).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view1', { templateUrl: 'partials/partials.html', controller: 'Myctrl1' });
$routeProvider.when('/view2', { templateUrl: 'partials/partials1.html', controller: 'Myctrl2' });
$routeProvider.otherwise({ redirectTo: '/view1' });
}]);
try this

Categories

Resources