Angularjs dependency injection in resolve - angularjs

I would like to use proper dependency injection in MyCtrl1to inject the fields of the MyCtrl1.resolve object. I've tried many different combinations of attempting to inject #MyCtrl1.resolve etc. with no luck.
#MyCtrl1 = ($scope, $http, batman, title) ->
$scope.batman = batman.data
$scope.title = title.data
#MyCtrl1.resolve = {
batman: ($http) ->
$http.get('batman.json')
title: ($http) ->
$http.get('title.json')
}
##MyCtrl1.$inject = ['$scope', '$http'] -- commented out because not sure how to inject resolve fields
angular
.module( 'app', [])
.config( ['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider)->
$locationProvider.html5Mode(true)
$routeProvider.when('/', {templateUrl: 'index.html', controller: MyCtrl1, resolve: MyCtrl1.resolve})
$routeProvider.otherwise({redirectTo: '/'})
])
angular.bootstrap(document,['app'])

Resolve is a property of a route and not a controller. Controllers would be injected with dependencies defined on a route level, there is no need to specify resolve properties on a controller.
Taking one of your examples (transformed to JavaScript), you would define your controller as always, that is:
MyCtrl1 = function($scope, $http, batman, title) {
$scope.batman = batman.data;
$scope.title = title.data;
}
and then the resolve property on a route:
angular.module('app', []).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true)
$routeProvider.when('/',{templateUrl: 'index.html', controller: MyCtrl1, resolve: {
batman: ['$http', function($http) {
return $http.get(..).then(function(response){
return response.data;
});
}],
title: ['$http', function($http) {
return //as above
}]
}});
$routeProvider.otherwise({redirectTo: '/'});
}]);
If you want to minify the code using resolve section of routing you need to use array-style annotations - I've included this in the example above.

Related

AngularJS Controller not registered

I'm new using Angular with MVC Web Api but using VB instead of C#. I'm trying to make an SPA web site and I have some week trying to solve this problem.
In my app.js I defined the routing to my views and the controllers I'm going to use in them
var goMessage = angular.module('goMessage', ['ngRoute', 'goMessage.controllers', 'goMessage.services', 'goMessage.directives']);
angular.module('goMessage.controllers', []);
angular.module('goMessage.services', []);
angular.module('goMessage.directives', []);
goMessage.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
//Vista Login
$routeProvider.when('/login/inicio', {
controller: 'loginController',
controllerAs: 'lgCtrl',
templateUrl: 'Home/Login'
});
//Vista Usuarios
$routeProvider.when('/usuarios/lista', {
controller: 'usuariosController',
controllerAs: 'usCtrl',
templateUrl: 'Home/Usuarios'
});
$routeProvider.when('/dashboard/inicio', {
controller: 'dashboardController',
controllerAs: 'dashCtrl',
templateUrl: 'Home/Dashboard'
});
$locationProvider.html5Mode(true);
}]);
The usuariosController.js controller is working very well, its code is:
angular.module('goMessage.controllers')
.controller("usuariosController", ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
//Ordenamiento por default
this.ordenarPorColumna = 'UsuarioID';
this.reverse = false;
// More code...
}
]);
And the loginController.js controller code is:
angular.module('goMessage.controllers')
.controller('loginController', ['$scope', '$http', 'ws', '$window', '$timeout', '$route',
function ($scope, $http, ws, $window, $timeout, $route) {
//DeclaraciĆ³n de variables
var me = this;
this.myData = "Data$$$";
}
]);
In the Login.vbhtml view I'm following the same pattern as the Usuarios.vbhtml view. I define my ng-app in the _layout.vbhtml and I don't define any controller inside any view.
The error I'm unable to solve is this:
Error Image
Look at the AngularJs Expression
As you can see, I've defined both controller using the same way but the only one that works is the usuarios one and any other controller I add doesn't work.
Here I show you the scripts loading order:
Scripts Loading Order
I'm using my local IIS and working in VS2012.
The angular JS version is 1.6.
To register the logic modules as controller, filter and etc..., you need to add this code in your app.config
var app = angular.module("App", []);
var config = function ($controllerProvider, $compileProvider, $filterProvider, $provide) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.register;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
//your codes
}
config.$inject = ["$controllerProvider", "$compileProvider", "$filterProvider", "$provide"];
app.config(config);
Why this happen?
sometimes we don't need to add all of controllers in our main index which has ng-view or ui-view for that we should put our controller as lazyload to the app.config as you do this in your config, because of that the main app for get the controllers need to register controllers and other modules.
This issue might happen due to asynchronous loading of scripts. The script order might also be an issue. You can add a console.log at the beginning of loginController to check whether the component is loaded correctly.

Angularjs template fails to work

I am working on an app about routing, my code:
//HTML, I passed a 'test' into routing
Test
<div data-ng-view=""></div>
//Template
<h1>{{res}}</h1>
//Angularjs
var app = angular.module("dictApp", ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/details/:test', {
templateUrl: 'template.html',
controller: 'testCtrl'
});
}]);
app.controller('testCtrl', function ($scope, $routeProvider) {
$scope.res = $routeProvider.test;
});
//The template is displayed as
{{res}}
The template page should display 'test', but I don't know why it didn't work.
Thansk in advance.
'test' parameter should be available in $routeParams.
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});
The service that exposes the route parameters is $routeParams. $routeProvider is the provider used to configure the routes in the app like the one you have done in your code using .when method as well
You need to inject $routeParams and use it instead of $routeProvider
app.controller('testCtrl', function ($scope, $routeParams) {
$scope.res = $routeParams.test;
});

Angular Routing Params issue

I am using a module where I add in my first controller which is taking a service as a dependency. All the service is doing is bringing in some data.
Then I have a show function which I am adding on an anchor element in my view in order to be able to click on the the first name and then get the user's details.
My second controller takes the data from the first controller and then using $routeParams I am trying to show the data on the user view.
Is there something I am doing wrong here?
(function() {
var app = angular.module('test');
app.controller('testCtrl', ['$scope', 'testFactory', '$location', function($scope, testFactory, $location) {
testFactory.getContact().then(function(data) {
$scope.contacts = data.data;
});
$scope.show = function(firstname) {
$location.path('main/' + firstname);
};
}]);
app.controller('userCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.user = $scope.contacts[$routeParams.firstname];
}]);
}());
These are the routes
(function() {
var app = angular.module('test', ["ngRoute"]);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "testCtrl"
})
.when("/main/:firstname", {
templateUrl: "contact.html",
controller: "userCtrl"
})
.otherwise({redirectTo:"/main"});
$locationProvider.html5Mode(true);
});
}());
This is the error I am getting in my console:
TypeError: Cannot read property 'any1' of undefined
where any1 is the is the first name.

angular sub module route

I have a:
main module : kp
sub module : kp.venue
I want kp.venue to have it's own "route" definitions (for all paths relative to that module).
This is what I am trying to achieve in the code bellow.
Can anyone explain me why it doesn't work?
I followed the technique presented in this post: https://stackoverflow.com/a/15301427/971008
(function () {
'use strict';
angular.module('kp.venue', [])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/venue", {
template : "<p>This is the venue module</p>",
controller: "VenueCtrl"
});
}
])
.controller('VenueCtrl', ['$scope',
function($scope){
console.log("VenueController");
}
]);
angular.module('kp', ['ngRoute', 'ngAnimate', 'kp.venue'])
.config(['$locationProvider', '$routeProvider',
function($locationProvider, $routeProvider) {
$locationProvider.html5Mode({enabled:true, requireBase:false});
$routeProvider
.when("/", {
template: "<p>main app</p>",
controller: "MainController"
})
.otherwise({
redirectTo: '/'
});
}
]);
//Load controller
angular.module('kp')
.controller('MainController', ['$scope',
function($scope) {
$scope.test = "Testing...";
}
]);
}());
Note that I have already tried to move "kp.venue" bellow the definition of "kp" module to be sure that it was not a problem related to things not being loaded in the right order.

Angular JS remove hash from URL not working

I am trying to get rid of the url looking like http://example.com/#/album/0 and have it look more like http://example.com/album/0.
I have the following code
(function() {
var app = angular.module('chp', ['ngRoute', 'projectControllers']);
app.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/directory.html',
controller: 'ProjectsCtrl'
}).
when('/album/:id', {
templateUrl: 'partials/album.html',
controller: 'ProjectDetailCtrl'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
var projectControllers = angular.module('projectControllers', []);
projectControllers.controller('ProjectsCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.projects = albums;
$scope.filters = { };
}]);
projectControllers.controller('ProjectDetailCtrl', ['$scope', '$routeParams', '$sce',
function($scope, $routeParams, $sce) {
$scope.project = albums[$routeParams.id];
})();
but this is causing my app the break entirely once I add in $locationProvider in the three places shown. Any idea as to why this is not working for me? Also I am including angular-route.js just after jquery and angular.js so that cant be the problem
At a glance it looks all right to me, but you must make sure your server is set up to serve http://example.com/index.html for any route, otherwise it will try to load http://example.com/album/0/index.html before bootstrapping your angular application. What do you see when you enable html5? 404 not found? Console error?
You might also need to add
<base href="/" /> inside <head></head> in your index.html file

Resources