Second call to angular.module causes routing to fail - javascript

I have an site I have put together based on a tutorial I found here
http://www.revillweb.com/tutorials/angularjs-in-30-minutes-angularjs-tutorial/
My app.js contains
angular.module('kolvir', ['ngRoute'])
.controller("kolvirController", function($http){
var vm = this;
vm.searchInput = '';
$http.jsonp (
'https://sfcons.azure-mobile.net/api/getcons/?
callback=JSON_CALLBACK')
.success(function (data){
vm.cons = data;
})
.error(function (data) {
console.log('ERROR');
});
});
I added a controller (gallery-controller.js )and routing appears to fail. After ripping things out I determined that adding the module call causes the failure, with:
angular.module('kolvir', ['ngRoute']);
Without it works just fine. I have a second site based on twitter bootstrap that uses the same pattern and it works just fine.
I am still new enough to angular I am not even certain what I should be searching for to find and answer, but so far I have not turned up anything similar to this.

Related

AngularJS: Controller loads only after page refresh

I am using AngularJS with ASP.NET MVC to create an application which uses Angular controllers for the front end.
When I run the application on my development system, it works fine. When I deploy it on my local IIS, it works fine. BUT, when I deploy it the to production server IIS, the angular controller does not load and it requires refreshing the page to get it to work.
I have looked at the similar questions, for instance:
Angular app only loads on page refresh
I also do not have any other extensions or plugins installed to affect the behavior as suggested in other similar questions.
I have moved all the JS in bundles, but that also to no avail. The order of the JS also seems to be correct because it works perfectly well on the development system, and local IIS.
I have no other idea on how to proceed with this issue.
Here's the screenshot for the error in the console:
And here's the code:
For HomeController,
app.controller('homeController', function ($scope, $uibModal, HomeService, RequestService) {
$scope.refreshOriginatorForms = function (searchCriteria) {
HomeService.getOriginatorRequestForms(searchCriteria).then(function (response) {
....
});
}
var originatorSearchCriteria = {
Pager: {
ItemsPerPage: 10,
CurrentPage: 1
}
};
$scope.OriginatorFormsSearchCriteria = originatorSearchCriteria;
$scope.initialize = function () {
$scope.refreshOriginatorForms($scope.OriginatorFormsSearchCriteria);
};
}
The $scope.initialize method is called in the view with ng-init="initialize()"
I have moved all the JS in bundles
If you are minimizing angular controllers then you should write our controller like this to that minimizers does not rename important angular keywords like $scope
app.controller('homeController',['$scope','$uibModal','HomeService','RequestService', function ($scope, $uibModal, HomeService, RequestService) {
$scope.refreshOriginatorForms = function (searchCriteria) {
HomeService.getOriginatorRequestForms(searchCriteria).then(function (response) {
....
});
}
var originatorSearchCriteria = {
Pager: {
ItemsPerPage: 10,
CurrentPage: 1
}
};
$scope.OriginatorFormsSearchCriteria = originatorSearchCriteria;
$scope.initialize = function () {
$scope.refreshOriginatorForms($scope.OriginatorFormsSearchCriteria);
};
}])
We finally got it solved. Our network engineer suggested enabling the CDN on the DNS, and it worked.
All this time, looking at the code, and the issue was something else.

variable not found / undefined after grunt build (uglify)

I am using AngularJS for building a simple app with a map. As the main ctrl had too many logic I build a second controller for the navbar. Until here everything worked fine. Now I outsourced the map.on('zoomend' ... ) function when refactoring the main controller.
The problem now is, that when the navbar controller file is minified (through grunt build uglify) I get the following error:
Cannot read on of undefined
That means, map is undefined even though it is declared at the top of the file AND I do not have the problem on localhost (grunt serve).
Navbar Ctrl:
'use strict';
angular.module('angularMapApp').controller('navbarController', navbarController);
navbarController.$inject = ['$scope', '$mdSidenav', 'helper', 'RespondService', 'shipTypes'];
function navbarController($scope, $mdSidenav, helper, RespondService, shipTypes) {
var map = RespondService.getMap();
map.on('zoomend', function() {
timestamp = RespondService.getTimestamp();
selectedShipTypes = RespondService.getSelectedShipTypes();
selectedShipState = RespondService.getSelectedShipState();
showGrid = RespondService.getShowGrid();
helper.loadAndShowShipMarkers(timestamp, selectedShipTypes, selectedShipState, showGrid, map).then(function(results) {
$scope.numberOfShips = results;
RespondService.setNumberOfShips($scope.numberOfShips);
});
});
So this is a short version of my controller. The grunt file is still the same as created with yeoman. I too logged the map value at the top of the file, and there it has a value. However using 'map.on' might not work.
Maybe anyone can help me with that.
Your $inject seems to be correct, so minify should work fine for angular injection. It looks like var map is loading data from RespondService.getMap(). What do you expect to get from that function? You might want to put a break point and see if what you expecting is being returned.

Angular Running Controller twice on browser reload

Problem:
I have an Angular app which works fine. It has 4 main page controllers which loaded inside the ng-view. All there controllers are connected to pages which routed via ngRoute.
When the app is loaded first time it works ok. But if I go to any of these pages and press browser's refresh(f5) the controllers are called twice. Is there any reason why they run once in the first instance and twice in a reload?
Common problem, you must have loaded your controller on ui-router and also in the HTML file. Just remove it from HTML file, always use router to inject controllers, its just good practice.
Sorry guys it was an issue with a promise with a return.
After login in I had following code
....
$scope.someMethod().then(function(_data){
...
if (something not related to _data) {
$route.reload();
} else {
$location.path("xcxcxcxcxcx");
}
...
})
in something method..
$scope.something = function(){
var deff = $q.defer();
....
APICALL.callAPI(xxxxx).then(function(data){
deff.resolve(data);
}, function(error) {
deff.reject();
});
return deff.promise;
};
The last return deff.promise returned the execution to the earlier method and ran $route..reload();
I am not 100% convinced but removing
return deff.promise;
solved the issue.

AngularJS ng-click not working, but ng-change is, when calling the same function

EDIT The code is all correct, the problem was because of including 'ngTouch', see my own answer below.
I am probably making some stupid mistake here, but for the life of me I cannot find it.
I have this piece of markup, which is correctly wired up with a controller:
<input type="text" ng-change="doStuff()" ng-model="stuff"/>
<button ng-click="doStuff()">doStuff</button>
The controller code:
console.log('Hi from controller');
$scope.stuff = "something";
$scope.doStuff = function() {
alert('doing stuff');
}
The problem is nothing happens when I click the button. If I change the input field, I get the alert, so ng-change works, but ng-click does not.
Let me know if this is not enough information, but I would not know what else to provide, and the general setup seems to be working fine...
The rest of the HTML does not contain any Angular directives, and it is loaded like this in myModule.config:
$stateProvider
.state('stuff', {
templateUrl: 'pages/stuff.html',
url: '/stuff',
controller: 'StuffCtrl'
})
and the controller is defined like this:
angular.module('myModule')
.controller('StuffCtrl', function ($scope) {
// above code
});
It turned out that the problem was with another dependency 'ngTouch'. I did not use it, but still it was loaded. My module did not even depend on it. (I am using that admin site template from here: http://startangular.com/product/sb-admin-angular-theme/). After removing loading of the ngTouch it worked as expected. I will file this as a bug to both projects as well... Thanks for your help!

Javascript \ Angular function help - mental block

I don't know what it is about JS, but I have a mental block. I apologize for the dumb question, but I'm at a loss because no matter how much I read I cannot get the academics into practice. Especially when it comes to nested functions.
I have a controller, lets say FileCtrl. Inside of it I have the the following that listens for file added to an input field via a directive. I'm attempting to inject an Angular JS factory service service called fileReader (a queue service for HTML5 FileReader).
However,I keep getting a undefined error on fileReader. I know why because, it cannot see fileReader, but injecting it at $scope.$on and then again on $scope.$apply doesn't work. Also, adding fileReader as a closure at the end of $scope.$on doesn't work either.
I should add that I can see the args.file and if I remove the fileReader code it will push the file no problem, but I then have no thumbnail. So I it works, just not with the fileReader and that is because Im doing something wrong with injection.
Side note, to Vals comment below I use apply as I found there was a image render sync issue without it which works fine for smaller images, but with larger images it freezes which is why I'm attempting to create and use a $q fileReader service. I suppose another way to solve for it would be to create a watch / directive on the array entry and when img comes back with the 64 encode string populate the html element ... like I said JS mental block :)
myApp.controller('FileController', ['$scope', 'FileReaderService', function($scope, FileReaderService ){
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
$scope.progress = 0;
fileReader.readAsDataUrl(args.file, $scope)
.then(function(result) {
$scope.imageSrc = result;
});
$scope.files.push(args.file);
});
});
});
In AngularJS not all functions are been processed by Dependency Injection. In Controllers, Directives (in definition of directive and in controller, not on link or compile), Servicies AngularJS inject requested instances, but in some other functions (like event listeners) arguments are passed by position.
In your case you need to put fileReader into definition on controller, not on event listener.
Also you need to remove apply because event listeners added via $on are included into digest loop.
Thanks to all for your replies. Val you made me go back and do a little more research and I found the answer with a little debugging. Not sure I understand why yet, but I have an idea.
If there is an error in your factory service, in my case, FileReaderService angular won't always explode when bootstrapping the service, will only explode when you call the service, which makes kind of makes sense. If something is wrong in the service the entire service will not boot. Also, you won't get any error message when injecting it into the controller. I had to place a watch on the module and noticed there was a reference error. I found I had a missing function.
Purely inexperience on my end, but I kept trying to capture the results form the $q service, which is was doing fine, but then attempting to inject to outside the $q return i.e. I was attempting to capture $scope.imageSrc = result and insert it post the .then, which doesn't work as you have a sync issue. I could see the value in the $scope.files, but it would not console.log or show up in HTML. So I moved all the file manipulation into the .then and it works perfectly. Logical when you think about it :) why have a $q if you not going to use it ... lol.
// problem code
fileReader.readAsDataUrl(args.file, $scope)
.then(function(result) {
$scope.imageSrc = result;
});
// cannot and should not try to work the results outside the return promise
$scope.files.imgSource = $scope.imageSrc;
$scope.files.push(args.file);
//Fixed and working code
myApp.controller('FileController', ['$scope', 'FileReaderService', function($scope, FileReaderService ){
var reader;
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.progress = 0;
var file = args.file;
FileReaderService.readAsDataUrl(file, $scope)
.then(function(result) {
file.imgSource = result;
$scope.files.push(file);
});
});
});

Categories

Resources