I have this angular app that I am running off only one webpage of my site.
I have a main application that uses another module I made as a dependency.
The problem I am having is that nothing inside my controller is being ran. Why won't my controller run?
My route does bring in the view however so I know that the module is working.
I got rid of my data service to be certain that it was not it.
The console.log before the function outputs, but nothing in the function runs.
I also have no console errors.
app.js:
(function(){
'use strict';
var dependencies = [
'ghpg',
'ngRoute'
];
angular.module('blogger', dependencies)
.config(Config);
Config.$inject = ['$locationProvider']
function Config($locationProvider){
$locationProvider.hashPrefix('!');
}
if (window.location.hash === '#_=_'){
window.location.hash = '#!';
}
//bootstrap angular
angular.element(document).ready(function(){
angular.bootstrap(document, ['ghpg']);
});
})();
module:
(function(){
'use strict';
var dependencies = [ 'ngRoute' ];
angular.module('ghpg', dependencies)
.run(init)
init.$inject = ['$rootScope','$location' ];
function init($rootScope, $location){
var vm = this;
}
})();
View:
<div class="container-fluid" data-ngController="blogController as vm">
<h2> Articles </h2>
<div class="post-listing" data-ng-repeat=" post in vm.data">
<p> {{ post }} </p>
</div>
</div>
Controller:
(function(){
'use strict';
angular
.module('ghpg')
.controller('blogController', blogController);
blogController.$inject = ['$scope'];
////
console.log("In controller file");
function blogController($scope){
console.log('running controller');
var vm = this;
vm.data = blogContent.getContent();
console.log(vm.data);
}
})();
I am wondering if it has something to do with bootstrapping my application? (But it all still works even without the explicit ng-app, so I am thinking that my bootstrapping does work)
My next best guess is that my controller in my html is not being set correctly, but every time I mess with it I either get the same result or an error in the console, and it still doesn't work.
blogController.$inject = ['$scope','blogController']
you're trying to inject your controller into your controller. Change it to
blogController.$inject = ['$scope'] and function blogController($scope).
Did you mean to write? blogController.$inject = ['$scope','blogContent']
I see you're calling a method on blogContent and I don't see it injected anywhere.
Edit
data-ngController should be data-ng-controller.
I am relatively new to angular and here is what I am trying to do:
I am trying to pre-compile angular templates into a view so that they can be shown instantaneously when the navigation event to the view occurs.
I am trying mock some kind of a navigation controller behavior for my app where the views preload or stack up and don't show in the SPA until their routes are active.
I did some research and $templateCache might not be something that would work for me since it seems to be only prefetching the template, viz. the uncompiled view (as per my limited understanding of angular), but what I am looking for is the "compiled version"; that is, the result of a $scope applied to a template.
Currently, the app's templates and controllers are linked through $routeProvider and ng-view constructs.
Minimal code skeleton:
JS:
var app = angular.module('airfiApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: ''
})
.when('/shop', {
templateUrl: 'views/shop.html',
controller: 'ShopController'
})
.otherwise({
redirectTo: "/index.html"
}))
});
app.controller('ShopController', ['ImageFetchService', function(ImageFetchService) {
ImageFetchService.get().then(function(images) {
$scope.images = images;
});
}]);
app.factory('ImageFetchService', ['$q', '$http', function($q, $http) {
var def = $q.defer();
//basically get product docs with id products:name-of-product
var couchdbURL = 'http://username:password#localhost:5984/db_name/_all_docs?startkey="products"&endkey="products\uffff"';
$http.get(couchdbURL).then(function() {
//do some processing and send back array of objects called 'images'
/* images =
[
{
... product information... ,
src: http://couchurl/db_name/product1/attachment_name
},
{
... product information... ,
src: http://couchurl/db_name/product2/attachment_name
}
.
.
.
]
*/
def.resolve(images)
});
}]);
HTML:
//index.html
<!DOCTYPE html>
<html>
<head>
<script src="/Scripts/angular.js"></script>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
</head>
<body>
<!-- some home page html -->
<section ng-view> </section>
</body>
</html>
//shop.html
<div ng-repeat = " img in images">
<img ng-src="img.src" alt="img.productName" />
</div>
I really don't think you need to compile the template manually - angular will do this for you. If you really insist, you can compile any template against any scope using $compile:
$compile( element.contents() )( scope );
What I really think you're after is loading of inline template. This question shows how it is done.
A couple things you can do to easily speed up how fast a view is rendered, first thing is you can pre-load the data by calling a pre-load method in a service, during the run phase of the App. Example
//service that has a preload function that stores an http result in memory
app.service('myService', function($http){
var data;
this.getData= function(){
return $http.get('dataUrl')
.success(function(data, status, headers, config) {
return data;
})
};
// calls get data and stores result in memory
this.preloadData = function(){
this.getData().then(function(data){
data = data;
});
};
// returns in memory result
this.getPreloadedData = function(){
return data;
};
});
// call preload in run block
app.run(function(myService){
// preloads data from service
myService.preloadData();
});
// get data from in memory
app.controller('TestCtrl', function($scope, myService) {
$scope.data = myService.getPreloadedData();
});
The second thing you can do is store the template in $template cache rather than fetching it form a http request, you can do this in the run block as well, and if you using gulp or grunt there are some great plug ins that provide a better way of doing this
app.run(function($templateCache){
// cache template
var tempalate = '<h2>hello world</h2>'
$templateCache.put('test.html', tempalate);
});
here is a plunk that goes into better detail and shows more examples
http://embed.plnkr.co/DSeWLVNoV2Fe0SJI3Bwa/preview
This does exactly preload the route but it will help performance :)
I have the Controller
function loginController($scope, $http, $cookieStore, $location) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
$scope.log_me = function() {
$scope.login_me = [];
var login_un = $scope.uservals;
var login_pwd = $scope.passvals;
var logs_me = "api call here";
$http.get(logs_me)
.success(function(response) {
$cookieStore.put('token', response.token);
$cookieStore.put('ex_Id', response.ExId);
$cookieStore.put('Cont_Id', response.contactId);
$cookieStore.put('email', response.email);
$cookieStore.put('name', response.name);
$scope.log_sess = response;
$scope.sess_id= response.ss_id;
alert($scope.sess_id);
if (response.status == "failure, invalid username or password") {
$('.login_error').show();
$('.login_error').html('Invalid username or password');
$('.login_error').delay(4000).fadeOut();
$('.loading').hide();
} else {
$location.path('/dashboard');
}
});
}
}
I have used the above controller in my login page and it is working fine. Now i want to use the same controller in another template and retrieve the value "$scope.sess_id"
My Template is
<div class="page" >
<style>
#report_loader object {
width: 100%;
min-height: 700px;
width:100%;
height:100%;
}
</style>
<div class="loading"> </div>
<section class="panel panel-default" data-ng-controller="loginController">
<div class="panel-body" style=" position: relative;">
<div id="report_loader" style="min-height:600px;">
{{sess_id}}
<script type="text/javascript">
$("#report_loader").html('<object data="https://sampleurl/contact/reports/members/sorted_list.html?ss_id=' + sess_id+' />');
</script>
</div>
</div>
</section>
</div>
I am unable to retrieve the value {{sess_id}} here. What should be done so that i can bring this value in my template
You're routing the user to the "dashboard" route upon successful log in. Even though it might feel like you're using the same "loginController" for both login and dashboard, it will be an entirely new instance of both the controller and $scope. Which is why the {{sess_id}} is not displaying on the dashboard template.
If you're following an MVC-like pattern of AngularJS, ideally you want to be creating a new controller for your dashboard template. See explanation: https://docs.angularjs.org/guide/controller#using-controllers-correctly
So, I would create a DashboardCtrl and share the sess_id between the two. There are plenty of examples out there of how to share data between controllers:
You can use a factory: Share data between AngularJS controllers
You can use $rootScope: How do I use $rootScope in Angular to store variables?
Hope it helps.
I would use the rootScope approach, but an easier way to do that is to simply create a 'global' variable.
In your main controller (not your login controller), define a global scope variable like this:
$scope.global = {};
Then in your login controller, modify your session id to use the global variable:
$scope.global.sess_id= response.ss_id;
alert($scope.global.sess_id);
Then in your html:
<div id="report_loader" style="min-height:600px;">
{{global.sess_id}}
It's simple and works like champ.
I would create a service :
services.sessionService = function(){
var sessionID = null;
this.setSessionID = function(id){
sessionID = id;
}
this.getSessionID = function(){
return sessionID;
}
}
then in your controller :
$scope.sess_id= response.ss_id;
alert($scope.sess_id);
sessionService.setSessionID( $scope.sess_id );
and in your dashboard controller :
$scope.sess_id = sessionService.getSessionID();
Approaches
Your question's answer has many approach. They are:
Using value or service, you can call it wherever your controllers need them.
Using $rootScope, this is very common and easy to use. Just define your $rootScope inside your main controller or whatever controller that called first and then you can call it from other controllers like any $scope behavior.
Using $controller service or usually called controller inheritance. Define this in controller function's parameter, then type $controller('ControllerNameThatIWantToInheritance', {$scope:$scope});
Maybe any other approach can be use to it. Each of them have strength and weakness.
Examples:
using value
.value('MyValue', {
key: null
})
.controller('MyCtrl', function ($scope, MyValue) {
$scope.myValue = MyValue;
})
you can modified MyValue from service too
using $rootScope
.controller('FirstCtrl', function ($scope, $rootScope) {
$rootScope.key = 'Hello world!';
})
.controller('SecondCtrl', function ($scope, $rootScope) {
console.log($rootScope.key);
})
will print 'Hello World', you can also use it in view <div>{{key}}</div>
using $controller
.controller('FirstCtrl', function ($scope) {
$scope.key = 'Hello world!';
})
.controller('SecondCtrl', function ($scope, $controller) {
$controller('FirstCtrl', {$scope:$scope});
})
Second controller will have $scope like first controller.
Conclusion
In your problem, you can split your controller for convenient. But if you dont' want to, try to define $scope.sess_id first. It will tell the Angular that your sess_id is a defined model, and angular will watch them (if you not define it first, it will be 'undefined' and will be ignored).
function loginController($scope, $http, $cookieStore, $location) {
var token = $cookieStore.get('token');
var conId = $cookieStore.get('Cont_Id');
var exId = $cookieStore.get('ex_Id');
$scope.sess_id = null //<- add this
$scope.log_me = function() {
$scope.login_me = [];
var login_un = $scope.uservals;
var login_pwd = $scope.passvals;
var logs_me = "api call here";
$http.get(logs_me)
.success(function(response) {
$cookieStore.put('token', response.token);
$cookieStore.put('ex_Id', response.ExId);
$cookieStore.put('Cont_Id', response.contactId);
$cookieStore.put('email', response.email);
$cookieStore.put('name', response.name);
$scope.log_sess = response;
$scope.sess_id= response.ss_id;
alert($scope.sess_id);
if (response.status == "failure, invalid username or password") {
$('.login_error').show();
$('.login_error').html('Invalid username or password');
$('.login_error').delay(4000).fadeOut();
$('.loading').hide();
} else {
$location.path('/dashboard');
}
});
}
}
So I have a bootstrap list:
<div class="ajax_company_list" ng-app="app">
<div class='list-group' ng-controller="PolicyController as policyCtrl">
<a href="#" class='list-group-item' ng-repeat="company in policyCtrl.companies">{{company.primary_name}}
</a>
<div id="loadingIcon" class='list-group-item'>
Loading...
</div>
</div>
</div>
Here is my Angular Javascript:
var app = angular.module('app', []);
app.controller('PolicyController', ['$scope', 'CompanyService', function($scope, CompanyService) {
$scope.companies = [
{
policy_number: 12345,
primary_name: "test"
}
];
$scope.getCompanies = function() {
CompanyService.fetchCompanies()
.success(function(data) {
$scope.companies = data.companies;
})
}
}]);
app.factory('CompanyService', ['$http', function($http) {
return {
fetchCompanies: function() {
return $http.get('http://spoonerinc:8886//json/glmod_Spooner-Inc?pagenum=1');
}
}
}]);
I basically have 2 questions. If I set $scope.companies equal to an array of objects, it does not show up but if I change $scope.companies to this.companies, it starts working again. Why is this?
2nd question, I can see the service call running in my net tab and can console.log the data and it reads fine. But it is not updating my actual list at all and I'm not sure what I'm doing wrong.
I am fairly new to Angular so if there is any advice on how I can do my code better, please let me know.
Thanks!
Because you are using the "Controller As" syntax, which effectively publishes the entire controller object to the scope.
What happens under the hood looks something like this:
function myCtrl($scope){
$scope['someAlias'] = this;
}
If you are going to use the controller as syntax, it's best to use a more object based approach instead of pushing things onto the $scope
Either on the prototype:
function myCtrl(companiesService){
this.companiesService = companiesService;
this.init();
}
myCtrl.prototype = {
init:function(){
var _this = this;
_this.companiesService.get()
.then(function(result){
_this.companies = result.data;
});
}
};
Or as closure style object:
function myCtrl(comapniesService){
var ctrl = {};
function init(){
companiesService.get()
.then(function(result){
ctrl.companies = result.data;
});
}
return ctrl;
}
For your second question, I think your problem is here:
ng-repeat="company in policyCtrl.companies"
You don't need to specify the controller as a prefix, since you've already declared it with ng-controller. It should be:
ng-repeat="company in companies"
And ng-controller to be:
ng-controller="PolicyController"
My guess is that the first problem will go away once you correct this.
This is a long shot, but has anyone seen this error before? I am trying to add 'Transporters' using express, angular and mongoDB. I get this error whenever I access a page ruled by the transporters controller:
Error: [ng:areq] http://errors.angularjs.org/1.2.12/ng/areq?p0=TransportersController&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native)
at http://localhost:3000/lib/angular/angular.min.js:6:450
at tb (http://localhost:3000/lib/angular/angular.min.js:18:360)
at Pa (http://localhost:3000/lib/angular/angular.min.js:18:447)
at http://localhost:3000/lib/angular/angular.min.js:62:17
at http://localhost:3000/lib/angular/angular.min.js:49:43
at q (http://localhost:3000/lib/angular/angular.min.js:7:386)
at H (http://localhost:3000/lib/angular/angular.min.js:48:406)
at f (http://localhost:3000/lib/angular/angular.min.js:42:399)
at http://localhost:3000/lib/angular/angular.min.js:42:67
The transporters controller looks like this:
'use strict';
angular.module('mean.transporters').controller('TransportersController', ['$scope', '$routeParams', '$location', 'Global', 'Transporters', function ($scope, $routeParams, $location, Global, Transporters) {
$scope.global = Global;
$scope.create = function() {
var transporter = new Transporters({
name: this.name,
natl_id: this.natl_id,
phone: this.phone
});
transporter.$save(function(response) {
$location.path('transporters/' + response._id);
});
this.title = '';
this.content = '';
};
$scope.remove = function(transporter) {
if (transporter) {
transporter.$remove();
for (var i in $scope.transporters) {
if ($scope.transporters[i] === transporter) {
$scope.transporters.splice(i, 1);
}
}
}
else {
$scope.transporter.$remove();
$location.path('transporters');
}
};
$scope.update = function() {
var transporter = $scope.transporter;
if (!transporter.updated) {
transporter.updated = [];
}
transporter.updated.push(new Date().getTime());
transporter.$update(function() {
$location.path('transporters/' + transporter._id);
});
};
$scope.find = function() {
Transporters.query(function(transporters) {
$scope.transporters = transporters;
});
};
$scope.findOne = function() {
Transporters.get({
transporterId: $routeParams.transporterId
}, function(transporter) {
$scope.transporter = transporter;
});
};
}]);
In my views I call the list and create methods. They generate the above error
I got this from the angular docs for ng:areq though still can't figure what's going on
AngularJS often asserts that certain values will be present and truthy
using a helper function. If the assertion fails, this error is thrown.
To fix this problem, make sure that the value the assertion expects is
defined and truthy.
Here's the view that calls the controller public/views/transporters/list.html:
<section data-ng-controller="TransportersController" data-ng-init="find()">
<ul class="transporters unstyled">
<li data-ng-repeat="transporter in transporters">
<span>{{transporter.created | date:'medium'}}</span> /
<h2><a data-ng-href="#!/transporters/{{transporter._id}}">{{transporter.name}}</a></h2>
<div>{{transporter.natl_id}}</div>
<div>{{transporter.phone}}</div>
</li>
</ul>
<h1 data-ng-hide="!transporters || transporters.length">No transporters yet. <br> Why don't you Create One?</h1>
</section>
Transporters service code:
angular.module('transporterService', [])
.factory('Transporter', ['$http', function($http){
// all return promise objects
return {
get: function(){
return $http.get('/api/transporters');
},
create: function(transporterData){
return $http.post('/api/transporters', transporterData);
},
delete: function(id){
return $http.delete('/api/transporters/'+id);
}
};
}]);
I experienced this error once. The problem was I had defined angular.module() in two places with different arguments.
Eg:
var MyApp = angular.module('MyApp', []);
in other place,
var MyApp2 = angular.module('MyApp', ['ngAnimate']);
I've gotten that error twice:
1) When I wrote:
var app = module('flapperNews', []);
instead of:
var app = angular.module('flapperNews', []);
2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:
index.html:
<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">
app.js:
var app = angular.module('flapperNews', []);
app.controller('MyCtrl', ....
In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".
There is actually an error message embedded in the error url:
Error: [ng:areq]
http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined
Here it is without the hieroglyphics:
MainCtrl not a function got undefined
In other words, "There is no function named MainCtrl. Check your spelling."
I ran into this issue when I had defined the module in the Angular controller but neglected to set the app name in my HTML file. For example:
<html ng-app>
instead of the correct:
<html ng-app="myApp">
when I had defined something like:
angular.module('myApp', []).controller(...
and referenced it in my HTML file.
you forgot to include the controller in your index.html. The controller doesn't exist.
<script src="js/controllers/Controller.js"></script>
I had same error and the issue was that I didn't inject the new module in the main application
var app = angular.module("geo", []);
...
angular
.module('myApp', [
'ui.router',
'ngResource',
'photos',
'geo' //was missing
])
Check the name of your angular module...what is the name of your module in your app.js?
In your TransportersController, you have:
angular.module('mean.transporters')
and in your TransportersService you have:
angular.module('transporterService', [])
You probably want to reference the same module in each:
angular.module('myApp')
I had this error too, I changed the code like this then it worked.
html
<html ng-app="app">
<div ng-controller="firstCtrl">
...
</div>
</html>
app.js
(function(){
var app = angular.module('app',[]);
app.controller('firstCtrl',function($scope){
...
})
})();
You have to make sure that the name in module is same as ng-app
then div will be in the scope of firstCtrl
The same problem happened with me but my problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
:)
I've got that error when the controller name was not the same (case sensitivity!):
.controller('mainCOntroller', ... // notice CO
and in view
<div class="container" ng-controller="mainController"> <!-- notice Co -->
I got this same error when I included the entire controller file name in the Routes like this:
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController.js'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController.js'
})
});
When it should be
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController'
})
});
Angular takes certain things you name like the app and controller and expounds on them in directives and across your app, take care to name everything consistently and check for this when debugging
I know this sounds stupid, but don't see it on here yet :). I had this error caused by forgetting the closing bracket on a function and its associated semi-colon since it was anonymous assigned to a var at the end of my controller.
It appears that many issues with the controller (whether caused by injection error, syntax, etc.) cause this error to appear.
This happened to me when I have multiple angular modules in the same page
I encountered this error when I used partial views
One partial view had
<script src="~/Scripts/Items.js"></script>
<div ng-app="SearchModule">
<div ng-controller="SearchSomething" class="col-md-1">
<input class="searchClass" type="text" placeholder="Search" />
</div>
</div>
Other had
<div ng-app="FeaturedItems" ng-controller="featured">
<ul>
<li ng-repeat="item in Items">{{item.Name}}</li>
</ul>
</div>
I had them in same module with different controller and it started working
I had the same error in a demo app that was concerned with security and login state. None of the other solutions helped, but simply opening a new anonymous browser window did the trick.
Basically, there were cookies and tokens left from a previous version of the app which put AngularJS in a state that it was never supposed to reach. Hence the areq assertions failed.
There's also another way this could happen.
In my app I have a main module that takes care of the ui-router state management, config, and things like that. The actual functionality is all defined in other modules.
I had defined a module
angular.module('account', ['services']);
that had a controller 'DashboardController' in it, but had forgotten to inject it into the main module where I had a state that referenced the DashboardController.
Since the DashboardController wasn't available because of the missing injection, it threw this error.
In my case I included app.js below the controller while app.js should include above any controller like
<script src="js/app.js"></script>
<script src="js/controllers/mainCtrl.js"></script>
I had done everything right other than setting controller in $stateProvider. I used filename rather than variable name.
Following code is wrong:
formApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('management', {
url: '/management',
templateUrl: 'Views/management.html',
controller: 'Controllers/ManagementController.js'
});
and this is the right approach;
formApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('management', {
url: '/management',
templateUrl: 'Views/management.html',
controller: 'ManagementController'
});
Make sure you noticed;
controller: 'ManagementController'
And for those who are curious about my controller file ManagementController.js, it looks like the this;
formApp.controller('ManagementController', ['$scope', '$http', '$filter', '$state',function(scope, http, filter, state) {
scope.testFunc = function() {
scope.managementMsg = "Controller Works Fine.";
};
}]);
For those who want a quick-start angular skeleton for above example check this link https://github.com/zaferfatih/angular_skeleton
The error will be seen when your controller could not be found in the application. You need to make sure that you are correct using values in ng-app and ng-controller directives
This happened to me when using ng-include, and the included page had controllers defined. Apparently that's not supported.
Controller loaded by ng-include not working
I have made a stupid mistake and wasted lot of time so adding this answer over here so that it helps someone
I was incorrectly adding the $scope variable(dependency)(was adding it without single quotes)
for example what i was doing was something like this
angular.module("myApp",[]).controller('akshay',[$scope,
where the desired syntax is like this
angular.module("myApp",[]).controller('akshay',['$scope',
// include controller dependency in case of third type
var app = angular.module('app', ['controller']);
// first type to declare controller
// this doesn't work well
var FirstController = function($scope) {
$scope.val = "First Value";
}
//Second type of declaration
app.controller('FirstController', function($scope) {
$scope.val = "First Controller";
});
// Third and best type
angular.module('controller',[]).controller('FirstController', function($scope) {
$scope.val = "Best Way of Controller";
});