AngularJS route resolve when calling controller using ng-include - javascript

Please see my plunkr here
https://plnkr.co/edit/hk7Z0jMwOfoUwJZ98F7a?p=preview
In my app.js I have two controllers and a routeprovider with a resolve for TestController
var app = angular.module('app', ['ngRoute']);
app.controller('DefaultController', ['$scope', function($scope){
$scope.welcome = "Hello World";
}]);
app.controller('TestController', ['$scope', 'context', '$routeParams', function($scope, context, $routeParams){
$scope.text = "TestController loaded!"
}]);
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
$routeProvider.
when('/test1',{
templateUrl: 'test1.html',
controller: 'TestController',
resolve: {
context: function(){return 'test';}
}
})
}])
In my html, I have an ng-include which should also load test.html in the default view
<body ng-controller="DefaultController">
<h1>{{welcome}}</h1>
<div ng-include="'test.html'" ng-controller='TestController'></div>
</body>
I cannot take the resolve out of the routeProvider as I still need it to when the user goes to '../test'
Is there any way I can resolve contextProvider from the ng-include?
or is there better ways to do this?
Any help would be greatly appreciated.

Create a factory/service and use that:
app.factory('fooResolver', function() {
return {
resolveMe: function() {
return 'test';
}
}
});
Now, use this in your router config:
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider){
$routeProvider.
when('/test1',{
templateUrl: 'test1.html',
controller: 'TestController',
resolve: {
context: function(fooResolver) {
return fooResolver.resolveMe();
}
}
})
}])
And do the same in your controller:
app.controller('TestController', ['$scope', 'fooResolver', '$routeParams', function($scope, fooResolver, $routeParams){
$scope.text = "TestController loaded!"
var context = fooResolver.resolveMe();
}]);

Related

Angular ng-view not displaying [leaning angular]

I'm learning Angular and I'm having problem on the routing. I've tried to solve it myself but have no idea what it can be.
Here's my script and a Plunker link of my script
var singleApp = angular.module('singleApp', ['ngRoute'])
.config([$routeProvider, $locationProvider, function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
// Deletes # in URL with HTML History API
$locationProvider.html5Mode(true);
}])
.controller('mainController', function($scope) {
$scope.message = 'This is the main page';
})
.controller('aboutController', function($scope) {
$scope.message = 'This is the about page';
})
.controller('contactController', function($scope) {
$scope.message = 'This is the message page';
});
I've imported the both angular and routing scripts in html.
The pages has just $message
The first issue is with your config. You're using a great practice by using an array for your injections but the first arguments must be strings. Change this:
.config([$routeProvider, $locationProvider, function($routeProvider, $locationProvider) {
to this
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
Then... remove this line:
$locationProvider.html5Mode(true);
Here's information about HTML5 mode:
https://docs.angularjs.org/error/$location/nobase
Enabling HTML 5 Mode in AngularJS 1.2
http://plnkr.co/edit/EXMiz3bAEttTQac0uvgh?p=preview
You have syntax error, config function should be like this
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
http://plnkr.co/edit/4csvt10yfolOepqECh51?p=preview
Removes the following line
//Deletes # in URL with HTML History API
$locationProvider.html5Mode(true);
Many of the errors and especially reference can view them in the browser console
You must modify the parameters of your config, should go well
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
Compare and see your code
var singleApp = angular.module('singleApp', ['ngRoute'])
singleApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
});
singleApp.controller('mainController', function($scope) {
$scope.message = 'This is the main page';
});
singleApp.controller('aboutController', function($scope) {
$scope.message = 'This is the about page';
});
singleApp.controller('contactController', function($scope) {
$scope.message = 'This is the message page';
});

AngularJS - 'Controller not a function: Seperate controller files

I am getting the 'Controller is not a function error in my application.
From what I have read the most common issue is that it the controller file is not referenced in the html page - this is not the case for me.
I do not get the error when I have included the controller in the same file as declaring the module, but when I am using seperate files for each controller.
Here is my folder structure:
app.js:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'assets/views/mainView.html',
controller: 'assets/controllers/mainController.js'
});
});
mainController.js
var myApp = angular.module('myApp');
myApp.controller('mainController', ['$scope', function($scope){
$scope.name = "test";
}]);
I have also read that when you declare a module, the array braces [] create a new module so I took them out of the module in mainController.js.
It works if I do this:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'assets/views/mainView.html',
controller: 'mainController.js'
});
});
myApp.controller('mainController', ['$scope', function($scope){
$scope.name = "hi";
}]);
I have referenced the controller like this in my index.html in the head section:
<script src="assets/scripts/js/app.js"></script>
<script src="assets/controllers/mainController.js"></script>
When you are having controller in another file no need to give path of the controller there which you have given in your config
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'assets/views/mainView.html',
//Remove this
//controller: 'assets/controllers/mainController.js'
//and then try this
controller: 'mainController'
});
});
Are you using IIFE? If not you should not assign angular module
var myApp = angular.module('myApp'); on your mainController.js as it overwrite your myApp variable since it is treated as globe variable.
If you want to apply IIFE your code should be:
app.js
(function () {
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'assets/views/mainView.html',
controller: 'mainController'
});
});
})();
mainController.js
(function () {
var myApp = angular.module('myApp');
myApp.controller('mainController', ['$scope', function($scope){
$scope.name = "test";
}]);
})();

Angular $routeParams empty object

I'm trying to get a query value from my url using angular's routeParams.
I've included angular-route in my html page:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>
Included Ng-Route in my app:
var app = angular.module('app', [
'ngRoute',
'reportController'
]);
And set up my controller as following:
var reportController = angular.module('reportController', []);
reportController.controller('CandidateCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
console.log(JSON.stringify($routeParams, null, 4));
$scope.person = $routeParams.person;
}]);
When I access the following URL, however, routeParams is an empty object: {}.
http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad
What am I doing wrong?
Edit:
I've configure the possible route - my routeParams object is still coming up null. I've tried:
famaApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/report:person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
}]);
and
when('/report?person', {templateUrl: 'Report.html', controller: 'CandidateCtrl'});
Rather then accessing like
http://localhost:8080/report?person=afe75cc7-fa61-41b3-871d-119691cbe5ad
try to access it like
http://localhost:8080/#/report/afe75cc7-fa61-41b3-871d-119691cbe5ad
you will get the guid in $route.Params
You have to set your routes to receive the arguments you want with $routeProvider..
Example:
app.config(['$routeProvider', '$locationProvider' function ($routeProvider, $locationProvider) {
$routeProvider
.when('/',
{
templateUrl: 'someHtmlUrl',
controller: 'someController',
controllerAs: 'someCtrl',
caseInsensitiveMatch: true
})
.when('/:person',
{
templateUrl: 'someHtmlUrl',
controller: 'someController',
controllerAs: 'someCtrl',
caseInsensitiveMatch: true
})
.otherwise(
{
templateUrl: 'someHtmlUrl'
});
$locationProvider.html5Mode(true); //Use html5Mode so your angular routes don't have #/route
}]);
Then you can just do
http://localhost:8080/afe75cc7-fa61-41b3-871d-119691cbe5a
And the $routeProvider will call your html and your controller as you can see with the .when('/:person'.. and then you can try and access your $routeParams and you will have your person there, $routeParams.person.

Angular Controllers Firing off more than once. Only certain ones

I have markup that has the following and then I have different sections of the app defined in different files. The problem I am running into is that the controllers that are on the main app page on load causes each of the nested controllers to run more than once. Any states that I change to with a click of the button are fine but these fire off 2-3 times each.
<html ng-app="myApp">
<body ng-controller="myController">
<div ng-controller="dashController">
<div ng-controller="listController">
</div>
</div>
</body>
</html>
My App.js
var myApp = angular.module('myApp', [
'user.profile',
'myApp.controllers',
'myApp.directives',
'ngCookies',
'ngAutocomplete',
'ui.router'
]).config(function($stateProvider, $urlRouterProvider, $locationProvider, $interpolateProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$urlRouterProvider.otherwise('/');
$stateProvider.
state('app', {
url: '/app',
templateUrl: '/views/homepage',
controller: 'MyCtrl1'
});
$locationProvider.html5Mode(true);
});
myApp.controllers
angular.module('myApp.controllers', ['ui.router','ngCookies']).
controller('myController', function ($scope, $http,$cookies) {
$scope.message = 'nothing to see here, move along';
if ($cookies.userdata) {
$cookies.userdata = $cookies.userdata.replace("j:", "");
console.log($cookies);
}
});
user.profile.js
angular.module('user.profile', [
'user.controllers',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'nouislider',
'ui.router',
'ui.bootstrap',
'ngLinkedIn'
])
.config(function($stateProvider, $urlRouterProvider, $locationProvider,$interpolateProvider, $linkedInProvider) {
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
$linkedInProvider.set('appKey', '753pos06f998t3')
.set('scope', 'r_fullprofile');
//.set('authorize', true);
$locationProvider.html5Mode(true);
$stateProvider
.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
});
user.controllers.js
angular.module('user.controllers', ['ui.router', 'ngAutocomplete', 'nouislider', 'ui.bootstrap', 'ngCookies', 'ngLinkedIn', 'angularFileUpload','cgPrompt'])
.directive('onLastRepeat', function () {
return function (scope, element, attrs) {
if (scope.$last) setTimeout(function () {
scope.$emit('onRepeatLast', element, attrs);
}, 1);
};
}).
controller('dashController', function ($scope, $state, $modal, $log, $http, $cookies) {
$scope.user = [];
}).
controller('listController', function ($scope, $http, $cookies) {
});
My app also doesn't initialize unless I run angular.bootstrap(document, ["myApp"]);
I don't think it is having the controller defined in the $stateProvider and the DOM... if I remove from the DOM none of the ng-clicks work even after the controller fires... also I have an ng-click that changes the state and it's controller is defined in the stateProvider and in the DOM and it does not fire twice... what is does is kick off the two other controllers again first before proceeding with it's action though.
The issue is that you are defining your controllers with the routeProvider / stateProvider ie:
$stateProvider.state('userDashboard', {
controller: 'dashController'
})
.state('userList', {
views : {
'popup' : {templateUrl: '/views/app/user/list/userList'}
},
controller: 'listController'
});
an you are redifining them in the DOM using
<div ng-controller="dashController">
remove one or the other but don't use the two at the same time, I'd suggest to remove the one declared in the DOM, ng-controller="dashController"
cheers

controller does not recognize routeParams variable passed from routeProvider

<script>
var app= angular.module('myApp', ['ngRoute', 'ngResource']);
app.factory('Greeter', ['$resource',function($resource){
return $resource(
'http://123.com/processor-url.php',{
},{
query: {
method:'GET',
/*params: { myvar: myvarActual },*/
isArray:true
}
}
);
}]);
app
.controller('appointmentController', ['$scope', 'Greeter',function($scope,$routeParams,Greeter){
alert($routeParams.myvar);
Greeter.query(function(data) {
$scope.output = data.myvar;
});
}]);
app.controller('homeController', ['$scope', function($scope){
}])
/*Final Config After Loading Everything*/
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/appointments/:myvar', {templateUrl: 'appointments.html', controller: 'appointmentController'});
$routeProvider.when('/home', {templateUrl: 'home.html', controller: 'homeController'});
$routeProvider.otherwise({redirectTo: '/home'});
}]);
</script>
In the above code, seems the controler is not even recognize myvar that was suppose to be included in the routeProvider's myvar. As the alert will show undefined, instead of the actually value of myvar (i.e. .../appointments/1066 ... if so I expect $routeParams.myvar = 1066, and alert($routeParams.myvar) should be 1066
$routeParams is missing from the dependency declaration so currently it's looking for myvar on Greeter which doesn't exist...
app
.controller('appointmentController', ['$scope', 'Greeter',function($scope,$routeParams,Greeter){
Should be...
app
.controller('appointmentController', ['$scope', '$routeParams', 'Greeter', function($scope, $routeParams, Greeter){

Categories