Controller name from scope of another controller - javascript

Can you help me please?
I want to set controller name which contains in scope of another controller.
JS file:
.controller('PageCtrl', [
'$http',
'$scope',
'$routeParams',
'$location',
function($http, $scope, $routeParams, $location){
switch($routeParams.page) {
case 'companies':
$scope.CurrentPageCtrl = 'CompaniesCtrl';
break;
default:
break;
}
}])
.directive('myPagecontent', function() {
return {
template: '<ng-controller ng-controller = "{{CurrentPageCtrl}}"></ng-controller>'
};
})
HTML file:
<ng-controller ng-controller = "PageCtrl">
<my-pagecontent></my-pagecontent>
</ng-controller>
And I get error:
angular.js:13642 Error: [ng:areq] Argument '{{CurrentPageCtrl}}' is not a function, got undefined

This can be a bit tricky since ng-controller in this case expects an expression that evaluates to a controller constructor function, not to a string that contains the controller name.
One way to solve it is by doing the following:
app.controller('PageCtrl', [
'$http',
'$scope',
'$location',
function($http, $scope, $location) {
$scope.CurrentPageCtrl = Controller1;
}
]);
function Controller1($scope) {
console.log('Controller1');
}
app.controller('Controller1', Controller1);
function Controller2($scope) {
console.log('Controller2');
}
app.controller('Controller2', Controller2);
app.directive('myPagecontent', function() {
return {
template: '<ng-controller ng-controller="CurrentPageCtrl"></ng-controller>'
};
});
Demo: http://plnkr.co/edit/s3yy2fdF5OgBjPcKWikw?p=preview
An alternative solution is to create a directive that runs before everything else, that takes a variable with the controller name, adds ng-controller with the correct value and then remove itselves.

Related

Trouble passing angular resolve values into controller

How do I pass the resolve validToken value to my controller?
Config:
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/recover/:token', {
templateUrl: 'recover.html',
controller: 'recoverCtrl',
resolve: {
validToken : function(){
return "INVALID TOKEN"
}
}
});
}])
Controller:
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope',
function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
// Rest of controller code.
}
]);
I would like to do this without removing the []'s so the code could eventually be minifed. The below example is working as I expected so I know that all of my code it working, I'm just not sure what I should add to the above code to make it function similarly.
.controller('recoverCtrl', function($location,$scope,$http,$routeParams,$rootScope,validToken) {
console.log(validToken);
//Other code
});
Figured it out thanks to Etsus.
I just needed to add the object key as a string while injecting and it was able to determine that it was a resolve key
.controller('recoverCtrl', ['$location','$scope','$http', '$routeParams', '$rootScope', 'validToken', function ($location, $scope, $http, $routeParams, rootScope, validToken) {
console.log(validToken);
}]);

Ionic/Angularjs change controller to a global Variable

Here is my controller:
(function () {
var app= angular.module('app');
app.controller('recommendedJobsCtrl', ['$scope', function(dataShare,$q,$scope, $ionicSideMenuDelegate,$window,$http,$timeout) {
// passes contents to jobDetails to be rendered and displayed
window.post = function($event, res){
console.log(angular.element($event.target).parent());
dataShare.sendData(res)
}
/**
* handles pagination
*loads first 3 pages
**/
var i=1;
window.result=[];
window.noMoreItemsAvailable=false;
window.loadMore = function()
{
console.log('here')
if(i<4)
{
$http.get( "http://test.website.com/api/search/"+i).success(function(response)
{
i++;
$scope.result=$scope.result.push(response);
console.log(response);
$timeout(function ()
{
$scope.result = response
});
$scope.$broadcast('scroll.infiniteScrollComplete');
});
}else
{
$scope.noMoreItemsAvailable=true;
}
}
]);
}());
I read that my controller was under 'user strict' so it can't access the variables or functions. So I placed the word 'window' to make it global. But now it doesn't access the function because the console won't print. How do I fix this?
Dependency Injection is incorrect:
app.controller('recommendedJobsCtrl', [
'dataShare',
'$q',
'$scope',
'$ionicSideMenuDelegate',
'$window',
'$http',
'$timeout',
function(
dataShare,
$q,
$scope,
$ionicSideMenuDelegate,
$window,
$http,
$timeout) {
// Your code ...
}]);
Your code should be specific to the controller. You should create function and variables either on $scope as in $scope.<functionName> = function() {} and $scope.noMoreItemsAvailable or private to the controller as in function <functionName>() {} or var noMoreItemsAvailable.
In case intention behind using window object is to use same code across controllers, you may put this code in a factory.

Undefined variable passing data using service

I have declared my app and have one controller (for demonstration purposes):
var module = angular.module("app", [])
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
$scope.printEntity = function () {
console.log(dataService.getEntityArray());
}
}]);
And a service:
module.factory("dataService", function () {
var entityArrayService = [1,2];
return {
getEntityArray: function () {
return entityArrayService;
}
};
});
When I call $scope.printEntity from my view, I'm always told dataService.getEntityArray() is undefined.
I've loaded the service as a dependency and declared my entityArrayService array outside of my return statement. I've looked high and low for an answer but to no avail. My goal is to share a piece of data between two controllers, but at the minute I can't even use one controller to retrieve data.
The service isn't loaded as a dependency. Change this line:
module.controller("modalCtrl", ["$scope", function ($scope, dataService) {
to this:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
You are using strict syntax for dependencies declaration. So if you add a parameter to your controller, you must add its declaration too.
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
}
You didn't inject dataService in your controller. Try with:
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
// ...
});
The injection of the service in the controller is missing:
please correct to:
...
module.controller("modalCtrl", ["$scope", "dataService", function ($scope, dataService) {
...
The other code is correct.

AngularJS: '$scope is not defined'

I keep getting '$scope is not defined' console errors for this controller code in AngularJS:
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
}
]);
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Where in my AngularJS MVC files should I be looking at to find problems with the $scope not being defined properly?
For others who land here from Google, you'll get this error if you forget the quotes around $scope when you're annotating the function for minification.
Error
app.controller('myCtrl', [$scope, function($scope) {
...
}]);
Happy Angular
app.controller('myCtrl', ['$scope', function($scope) {
...
}]);
Place that code inside controller:-
angular.module('articles').controller('ArticlesController', ['$scope', '$routeParams', '$location', 'Authentication', 'Articles',
function($scope, $routeParams, $location, Authentication, Articles){
$scope.authentication = Authentication;
$scope.create = function() { // THROWS ERROR ON THIS INSTANCE OF $SCOPE
var article = new Articles({
title: this.title,
content: this.content
});
article.$save(function(response) {
$location.path('articles/' + response._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
}
]);
Just put you $scope.create function inside your controller. Not outside !
$scope is only defined in controllers, each controller have its own. So write $scope outside your controller can't work.
Check scope variable declared after controller defined.
Eg:
var app = angular.module('myApp','');
app.controller('customersCtrl', function($scope, $http) {
//define scope variable here.
});
Check defined range of controller in view page.
Eg:
<div ng-controller="mycontroller">
//scope variable used inside these blocks
<div>

Angular directive controller: Argument is not a function, got undefined

I have created a directive inside my controller, which i want to include another controller to the directive. The error i get back is Error: [ng:areq] Argument 'js/controllers/testview/DocumentController.js' is not a function, got undefined
TestviewController
app.controller('TestviewController', ['$http', '$scope', '$sessionStorage', '$state', '$log', 'Session', 'api', function ($http, $scope, $sessionStorage, $state, $log, Session, api) {
var module_id = $state.params.id;
$http.get(api.getUrl('componentsByModule', module_id))
.success(function (response) {
$scope.components = response;
});
}]);
app.directive('viewDoc', function () {
return {
templateUrl: "tpl/directives/testview/document.html",
controller: "js/controllers/testview/DocumentController.js",
resolve: { components: function() { return $scope.components }}
};
});
DocumentController
app.controller('DocumentController', ['$http', '$scope', '$sessionStorage', '$state', '$log', 'Session', 'api', 'components', function ($http, $scope, $sessionStorage, $state, $log, Session, api, components) {
$scope.components = components;
}]);
I'm pretty new with directices, but does anyone have any idea what I'm doing wrong?
Inside the directive definition object, the controller property expects a string with the function name, or the function itself (not the path to script file).
app.directive('viewDoc', function () {
return {
...
controller: "DocumentController",
};
});
You want to call the controller by name, not by file name:
controller: "js/controllers/testview/DocumentController.js"
should be
controller: "DocumentController"
There is no option to put controller by its URL in the directive definition. However if you define your controller in DOM template you could use controller: 'myController as myCtrl' in directive definition
are you sure you need a directive controller? i think what you are trying to achieve is link function.
you can use directive link functions like controllers.
.directive('myDialog', function() {
return {
restrict: 'E',
transclude: true,
scope: {},
templateUrl: 'my-dialog.html',
link: function (scope, element) {
scope.name = 'Jeff';
}
};
});
take a look at angular docs
https://docs.angularjs.org/guide/directive

Categories