Passing an object from route to Controller via Route Provider resolve - angularjs

I am trying to pass a variable from the resolve method of the $routeProvider to the controller that would be used for this route.
but what happens is the object is being resolved but the controller does not wait till the resolution of the object.
here is a snippet from the code i am using:
app.config(["$locationProvider", "$routeProvider", "$httpProvider", function ($locationProvider, $routeProvider, $httpProvider) {
$locationProvider.hashPrefix('');
.when("/EditProduct/:id",
{
templateUrl: "App/Products/editProductView.html",
controller: "EditProductCtrl as vm",
resolve: {
product: function (productsResource, $route, $routeParams) {
console.log($route.current.params.id);
return productsResource.getProductById().get({ id: $route.current.params.id }, function (data) {
console.log("inside the resolved function");
console.log(data.Name);
return data;
})
}
}
})
.otherwise({ redirectTo: "/" });
so the log message with the name from the app.js statement is shown.
while the controller has the supposedly resolved product injected as follows:
(function () {
"use strict";
angular.module("ProductManagementTool").controller("EditProductCtrl", ["product","productsResource", "currentUser", EditUserCtrl]);
function EditProductCtrl(product, productsResource, currentUser) {
var editCtrlViewModel = this;
console.log("the full name is " + product.Name);
editCtrlViewModel.product = product;
editCtrlViewModel.title = "Edit: " + product.Name;
}
}());
while the log message in the controller is shown as undefined.
i am using angular js 1.6.1 .

Controller won't wait, cause resolved element is a Promise returned by $resource (I presume you use $resource). You should make something like this:
var editCtrlViewModel = this;
product.$promise.then(function (element) {
editCtrlViewModel.product = element;
editCtrlViewModel.title = "Edit: " + element.Name;
})

Related

Angular Routing and Binding data from controller

I have my angular routing like th below code
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
}).when('/DeclarationAndIndemnityBond.html', {
templateUrl: '/DeclarationForms/V1/DeclarationAndIndemnityBond.html',
controller: 'declarationController'
}).otherwise({
redirectTo: "/"
});
app.controller('empController', function ($scope, $http) {
var resultPromise = $http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
resultPromise.success(function (data) {
console.log(data);
$scope.employeeProfile = data;
});
});
});
The empController calls my controller action with a parameter as per the code
$http.get("../ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
The controller's action code is as follows
[HttpGet]
[AllowAnonymous]
public ActionResult GetData(string ProcName)
{
if(Session["UserJDRECID"]==null || Session["UserJDRECID"].ToString()=="0")
{
return RedirectToAction("Login", "User_Login");
}
else
{
var UsrJDID = Convert.ToInt32(Session["UserJDRECID"]);
DataSet dt = Helper.PopulateData(ProcName, UsrJDID);
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(dt);
return Json(JSONString, JsonRequestBehavior.AllowGet);
}
}
The form get loaded properly as per the code
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
but it don't call my action GetData from where I suppose to bind the EmployeeProfile.html
If I change my angular controller like below code this still don't work
app.controller('empController', function ($scope)
{
console.log("hi"); alert();
});
My console gives below error
Error: error:areq
Bad Argument
Please help me I stuck here.
Thanks in advance.
You can't use "../" inside your $http.get.
I don`t know how your project is setup, but you can try:
$http.get("/ViewForms/GetData/", { params: { ProcName: "SP_EmployeeProfile_GetList" } });
In that case the ViewForms is the name of your controller and it needs to be in the root or pass the complete url. Make sure you are passing all the folders then Controller then your action.
Example: http://www.dotnetcurry.com/angularjs/1202/angular-http-service-aspnet-mvc
I change my code as follows and this worked for me.
var app = angular.module('mainApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: '/DeclarationForms/V1/EmployeeProfile.html',
controller: 'empController'
})
otherwise({
redirectTo: "/"
});
});
app.controller('empController', ['$scope', '$http', EmployeeProfile]);
function EmployeeProfile($scope, $http) {
$http.get("../ViewForms/GetData", { params: { ProcName: "SP_EmployeeProfile_GetList" } })//Done
.then(function (response) {
var mydata = $.parseJSON((response.data));
$scope.employeeProfile = $.parseJSON(mydata);
});
}

Controller Undefined after Form Submit: Argument 'RegistrationController' is not a function, got undefined

I wrote some custom routing in my app configuration file to handle routing of all my html templates and controllers instead of having to specifically define the route for every single html and controller. I have a Registration.html and RegistrationController.js under my Modules/Account/ directory. My app can find the controller the first time I go to it and I can fill out the page and submit the form on the page. After I submit successfully, I get redirected to a success page. When I try to go back to the same registration html/controller the 2nd time, it can find my html template, but it can not find my controller anymore and i get the error "Argument 'RegistrationController' is not a function, got undefined". Can anyone tell me why and how to fix this?
Please note this error only happens after a form submit. If I leave the page and go back to it without doing a form submit, everything works fine.
App Config
define(['angularAMD', 'angular-route', 'ui-bootstrap', 'ui-grid'], function (angularAMD) {
var app = angular.module("MyApp", ['ngRoute', 'ui.bootstrap', 'ui.grid']);
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", angularAMD.route({
templateUrl: function (rp) { return 'Modules/Account/login.html'; },
controllerUrl: 'Modules/Account/LoginController'
}))
.when("/:module/:page", angularAMD.route({
templateUrl: function (rp) { return 'Modules/' + rp.module + '/' + rp.page + '.html'; },
resolve: {
load: ['$q', '$rootScope', '$location', function ($q, $rootScope, $location) {
var path = $location.path();
var parsePath = path.split('/');
var parentPath = parsePath[1];
var controllerName = parsePath[2];
var loadController = "Modules/" + parentPath + "/" + controllerName + "Controller";
debugger;
var deferred = $q.defer();
require([loadController], function () {
$rootScope.$apply(function () {
deferred.resolve();
});
});
return deferred.promise;
}]
}
}))
.otherwise({ redirectTo: '/' });
}]);
loadDirectives(app);
angularAMD.bootstrap(app);
return app;
});
RegistrationController
define(['app-config','accountService'], function (app) {
app.register.controller('RegistrationController', ['$scope', '$rootScope', '$location', '$uibModal', 'accountService',
function ($scope, $rootScope, $location, $uibModal, accountService) {
$rootScope.applicationModule = "Account";
$scope.registerUserSuccess = function (response, status) {
debugger;
$location.path("/Account/RegistrationSuccess");
}
$scope.registerUserFailure = function (response, status) {
if (!response.ValidationErrors) {
$scope.ErrorList = [];
$scope.ErrorList.push("An error occurred. Please contact the system's administrator");
}
else {
$scope.ErrorList = response.ValidationErrors;
}
}
$scope.onSubmitClick = function (isValid) {
if (isValid) {
accountService.registerUser($scope.regModel, $scope.registerUserSuccess, $scope.registerUserFailure);
}
}
$scope.onCancelClick = function () {
$location.path("/Login");
}
}
]);
});
I haven't honed in on the answer yet, but I've noticed some refactoring that you should do that might get you closer to figuring out your problem ...
Stop using controllers. Use components, which were introduced in 1.5. These are superior in their reusability. They are more flexible in how you can use them and in what you can pass into them. The only controllers you should be using are the ones in components.
Stop using $scope or $rootScope for anything. Used named controllers. This is the default setting for a component.
Consider ui-router over angular-route. It's just a lot better.
What is loadDirectives(app) doing?
Put a log statement in your RegistrationContoller.js and just verify that it isn't being called more than once. If it thinks RegistrationController is undefined after previously being defined, it just feels like it's being defined more than once.
Is there anything fishy in accountService.registerUser? Is this function forwarding you to the success screen? That's kind of weird... seems to me that the accountService.registerUser should return a promise, and the onSubmitClick should resolve the promise and forward the user.
Try forwarding back to the RegistrationController at different points in the code, and try to narrow down the exact point that it becomes undefined. I think that you have some code running somewhere that you don't think you do.

AngularAMD + ui-router + dynamic controller name?

I'm trying to write a generalized route in my application and resolve the view and controller names on the fly based on the route params.
I have the following code that works:
$stateProvider.state('default', angularAMD.route({
url: '/:module/:action?id',
templateUrl: function (params) {
var module = params.module;
var action = module + params.action.charAt(0).toUpperCase()
+ params.action.substr(1);
return 'app/views/' + module + '/' + action + 'View.html';
},
controller: 'userController',
}));
However, I'm unable to figure out a way to resolve the controller name dynamically. I tried using resolve as described here, but ui-router seems to handle resolve differently than angular-route.
Any pointers?
EDIT: I've already tried using controllerProvider but it doesn't work for me (for instance, the following code just returns a hard coded controller name to test whether it actually works):
controllerProvider: function () {
return 'userController';
}
Gives me the following error:
Error: [ng:areq] Argument 'userController' is not a function, got undefined
http://errors.angularjs.org/1.3.3/ng/areq?p0=userController&p1=not%20aNaNunction%2C%20got%20undefined
This is a link to working plunker.
solution
We need two features of the UI-Router:
resolve (to load the missing pieces of js code)
controllerProvider (see cites from documentation below)
angularAMD - main.js definition
This would be our main.js, which contains smart conversion controllerName - controllerPath:
require.config({
//baseUrl: "js/scripts",
baseUrl: "",
// alias libraries paths
paths: {
"angular": "angular",
"ui-router": "angular-ui-router",
"angularAMD": "angularAMD",
"DefaultCtrl": "Controller_Default",
"OtherCtrl": "Controller_Other",
},
shim: {
"angularAMD": ["angular"],
"ui-router": ["angular"],
},
deps: ['app']
});
controllers:
// Controller_Default.js
define(['app'], function (app) {
app.controller('DefaultCtrl', function ($scope) {
$scope.title = "from default";
});
});
// Controller_Other.js
define(['app'], function (app) {
app.controller('OtherCtrl', function ($scope) {
$scope.title = "from other";
});
});
app.js
Firstly we would need some method converting the param (e.g. id) into controller name. For our test purposes let's use this naive implementation:
var controllerNameByParams = function($stateParams)
{
// naive example of dynamic controller name mining
// from incoming state params
var controller = "OtherCtrl";
if ($stateParams.id === 1) {
controller = "DefaultCtrl";
}
return controller;
}
.state()
And that would be finally our state definition
$stateProvider
.state("default", angularAMD.route({
url: "/{id:int}",
templateProvider: function($stateParams)
{
if ($stateParams.id === 1)
{
return "<div>ONE - Hallo {{title}}</div>";
}
return "<div>TWO - Hallo {{title}}</div>";
},
resolve: {
loadController: ['$q', '$stateParams',
function ($q, $stateParams)
{
// get the controller name === here as a path to Controller_Name.js
// which is set in main.js path {}
var controllerName = controllerNameByParams($stateParams);
var deferred = $q.defer();
require([controllerName], function () { deferred.resolve(); });
return deferred.promise;
}]
},
controllerProvider: function ($stateParams)
{
// get the controller name === here as a dynamic controller Name
var controllerName = controllerNameByParams($stateParams);
return controllerName;
},
}));
Check it here, in this working example
documentation
As documented here: $stateProvider, for a state(name, stateConfig) we can use controller and controllerProvider. Some extract from documentation:
controllerProvider
...
controller (optional) stringfunction
Controller fn that should be associated with newly related scope or the name of a registered controller if passed as a string. Optionally, the ControllerAs may be declared here.
controller: "MyRegisteredController"
controller:
"MyRegisteredController as fooCtrl"}
controller: function($scope, MyService) {
$scope.data = MyService.getData(); }
controllerProvider (optional) function
Injectable provider function that returns the actual controller or string.
controllerProvider:
function(MyResolveData) {
if (MyResolveData.foo)
return "FooCtrl"
else if (MyResolveData.bar)
return "BarCtrl";
else return function($scope) {
$scope.baz = "Qux";
}
}
...
resolve
resolve (optional) object
An optional map<string, function> of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them ALL to be resolved before the controller is instantiated...
I.e. let's use controllerProvider:
... to resolve the controller name dynamically...
In case, that you managed to get here, maybe you'd like to check another similar solution with RequireJS - angular-ui-router with requirejs, lazy loading of controller

Loading controller on demand using AngularJS and RequireJS

I'm using Angular UI-router and trying to download/load controller when the routing changes. I used resolve and category, the data.data returns the js file content as string. I'm not sure to make the controller available to angular. Please help
My module.js contains below routing code
state("privacy", {
url: "/privacy",
controllerProvider: function ($stateParams) {
return "PrivacyController";
},
resolve: {
category: ['$http', '$stateParams', function ($http, $stateParams) {
return $http.get("js/privacy.js").then(function (data) {
return data.data;
});
} ]
},
templateUrl: localPath + "templates/privacy.html"
})
The below controller exist in "js/privacy.js"
socialinviter.controller("PrivacyController", function ($scope) {
$scope.me = "Hellow world";
});
I also tried with require js but I'm getting error "http://errors.angularjs.org/1.2.16/ng/areq?p0=PrivacyController&p1=not%20aNaNunction%2C%20got%20undefined"
resolve: {
deps: function ($q, $rootScope) {
var deferred = $q.defer(),
dependencies = ["js/privacy"];
require(dependencies, function () {
$rootScope.$apply(function () {
deferred.resolve();
});
deferred.resolve()
})
return deferred.promise;
}
}
I have resolved the issue and I thought the solution would be helpful for others
Step 1: On your config, include the parameter $controllerProvider
mytestapp.config(function ($stateProvider, $controllerProvider)
Step 2: telling angular to register the downloaded controller as controller, add the below inside the config
mytestapp.config(function ($stateProvider, $controllerProvider) {
mytestapp._controller = mytestapp.controller
mytestapp.controller = function (name, constructor){
$controllerProvider.register(name, constructor);
return (this);
}
......
Step 3: Add the resolve method as below
state("privacy", {
url: "/privacy",
controller: "PrivacyController",
resolve: {
deps : function ($q, $rootScope) {
var deferred = $q.defer();
require(["js/privacy"], function (tt) {
$rootScope.$apply(function () {
deferred.resolve();
});
deferred.resolve()
});
return deferred.promise;
}
},
templateUrl: "templates/privacy.html"
})

Using resolve in $routeProvider causes 'Unknown provider ...'

I am trying to do an asynchronous http request to load some data before my app loads and so I am using a resolve in $routeProvider which is an http request in my MainController. For some reason, I keep getting Error: [$injector:unpr] Unknown provider: appDataProvider <- appData where appData is where I do my http request. I am using AngularJS v 1.2.5.
Here is the code and two methods that I tried that both give the same error:
Method #1
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(appData.data);
}
];
MainController.loadData = {
appData: function($http, $location, MainFactory){
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}
};
app.js
var app = angular.module('HAY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: MainController.loadData
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
I tried changing the name in case it was a conflicting system reserved keyword but with no luck. For some reason, appData is never recognized
Method #2
I also tried changing it around like so:
app.js
var app = angular.module('HEY', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
redirectTo: '/pages/alerts'
})
.when('/pages/:pageName', {
templateUrl: function(params) {
return 'views/pages/' + params.pageName + '.html';
},
controller: MainController,
resolve: {
appData: ['$http', '$location','MainFactory', function($http, $location, MainFactory) {
var aid = MainFactory.extractAid($location);
return $http({method: 'GET', url: URL_CONST + aid});
}]
}
})
.otherwise({
redirectTo: '/pages/alerts'
});
});
MainController.js
var MainController = ['$scope','$location','appData',
function($scope, $location, appData){
console.log(resolvedData);
}
];
However, the result was exactly the same. Does this have something to do with angular 1.2.5 ?
Here is a working version from someone else
http://mhevery.github.io/angular-phonecat/app/#/phones
And here is the code:
function PhoneListCtrl($scope, phones) {
$scope.phones = phones;
$scope.orderProp = 'age';
}
PhoneListCtrl.resolve = {
phones: function(Phone) {
return Phone.query();
},
delay: function($q, $defer) {
var delay = $q.defer();
$defer(delay.resolve, 1000);
return delay.promise;
}
}
angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve}).
otherwise({redirectTo: '/phones'});
}]);
Here's an example of the code I've used in the application I'm working on, not sure it will help much because its not much different than how you have it already.
Routing
.when('/view/proposal/:id',{
controller : 'viewProposalCtrl',
templateURL : 'tmpls/get/proposal/view',
resolve : viewProposalCtrl.resolveViewProposal
})
Controller
var viewProposalCtrl = angular.module('proposal.controllers')
.controller('viewProposalCtrl',['$scope','contacts','details','rationale',
function($scope,contacts,details,rationale){
$scope.contacts = contacts;
$scope.details = details;
$scope.rationale = rationale;
// [ REST OF CONTROLLER CODE ]
});
// proposalSrv is a factory service
viewProposalCtrl.resolveViewProposal = {
contacts : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Contacts',$route.current.params.id)
.then(function(data){
return data.data.contacts;
},function(){
return [];
});
}],
details : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Details',$route.current.params.id)
.then(function(data){
return data.data.details;
},function(){
return {};
});
}],
rationale : ['$route','proposalSrv',function($route,proposalSrv){
return proposalSrv.get('Rationale',$route.current.params.id)
.then(function(data){
return data.data.rationale;
},function(){
return {};
]
}]
};
Now that I think about it, when I was developing my application I did have a problem and not sure why when I named my resolve function "resolve." This gave me a problem:
.when('/path',{
// stuff here
resolve : myCtrlr.resolve
})
but this did not:
.when('/path',{
//stuff here
resolve : myCtrlr.myResolveFn
})
Another Possibility
The only other thing I can think of, is that you're returning the promise from the $http call and then trying to use appData.data Try using the .then function or one of the other functions (.success,.error) to retrieve the information from the promise.
The problem was NOT due to previously using different version of AngularJS.
Here are the fixes using the code that I have above.
In app.js, you need to declare the controller as controller: 'MainController' and NOT as controller: MainController even though you have var MainController = app.controller('MainController', ....).
Second and biggest thing was that in my index.html I declared my controller already like so:
index.html
body ng-app="HEY" controller="MainController" /body
This was causing the whole Unknown provider error Apparently angular wont tell you that you have already declared the controller that you are using to do the resolve it and that that will cause a weird error that have nothing to do with the resolve.
I hope this helps someone who may have the same problem.
One thing I noticed in angular 1x docs is that YOU DO NOT SPECIFY THE RESOLVED PARAMETER AS AN ANNOTATED DEPENDENCY
So this:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
'resolvedFromRouter'
Controller
]
function Controller($scope, someService, resolvedFromRouter) {
// <= unknown provider "resolvedFromRouter"
}
is wrong. You don't specify the resolved parameter as a dependency, in the docs:
For easier access to the resolved dependencies from the template, the resolve map will be available on the scope of the route, under $resolve (by default) or a custom name specified by the resolveAs property (see below). This can be particularly useful, when working with components as route templates.
So just do this instead:
.when('/somewhere', {
template: '<some-component></some-component>',
resolve: {
resolvedFromRouter: () => someService.fetch()
}
})
export default [
'$scope',
'someService',
Controller
]
function Controller($scope, someService) {
$scope.$resolve.resolvedFromRouter; // <= injected here
}

Resources