I have a problem where I'm trying to ng-show a view using ng-view when the user is logged in. By default the value vm.isLoggedIn is false when the controller initializes and vm.isLoggedIn gets set to true when they are logged in.
But this doesn't update the UI to reflect the changes, the ng-show will still have class="ng-hide", which is put there by AngularJS when you decalred it with ng-show.
How do I get the UI to reflect the changes when vm.isLoggedIn is updated to true on a return of a promise?
Here is the HTML:
<div id="loggedInContainer" ng-show="vm.isLoggedIn">
<div ng-view></div>
</div>
This is my controller where everything is being set:
(function () {
"use strict";
var app = angular.module("productManagement");
var MainCtrl = function ($scope, $timeout, userAccount) {
var vm = this;
vm.isLoggedIn = false;
vm.message = "";
vm.userData = {
userName: "",
email: "",
password: "",
confirmPassword: ""
};
var applyChanges = function () {
$timeout(function () {
$scope.$apply();
});
}
vm.registerUser = function () {
vm.userData.confirmPassword = vm.userData.password;
vm.userData.userName = vm.userData.email;
userAccount.registration.registerUser(vm.userData, function (data) {
vm.confirmPassword = "";
vm.message = "Registration Successful";
vm.login();
}, function (errorResponse) {
vm.isLoggedIn = false;
vm.message = errorResponse.statusText + "\r\n";
if (errorResponse.data.exceptionMessage) {
vm.message += errorResponse.data.exceptionMessage;
}
// Validation Errors
if (errorResponse.data.modelState) {
for (var key in errorResponse.data.modelState) {
vm.message += errorResponse.data.modelState[key] + "\r\n";
}
}
});
}
vm.login = function () {
vm.userData.grant_type = "password";
vm.userData.userName = vm.userData.email;
userAccount.login.loginUser(vm.userData, function (data) {
vm.isLoggedIn = true; // This is where vm.isLoggedIn is set to true
vm.message = "";
vm.password = "";
vm.token = data.access_token;
//$("#loggedInContainer").removeClass("ng-hide"); // Hack used to manually remove the class
}, function (errorResponse) {
vm.password = "";
vm.isLoggedIn = false;
vm.message = errorResponse.statusText + "\r\n";
if (errorResponse.data.exceptionMessage) {
vm.message += errorResponse.data.exceptionMessage;
}
if (errorResponse.data.error) {
vm.message += errorResponse.data.error;
}
});
}
}
app.controller("MainCtrl", ["$scope", "$timeout", "userAccount", MainCtrl]);
})();
This is the service I'm using to Login the user, which uses $resource
(function () {
"use strict";
var app = angular.module("common.services");
var userAccount = function ($resource, $http, appSettings) {
return {
registration: $resource(appSettings.serverPath + "/api/Account/Register", null,
{
"registerUser": { method: "POST" }
}),
login: $resource(appSettings.serverPath + "/Token", null,
{
"loginUser": {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
transformRequest: function (data, headersGetter) {
var str = [];
for (var d in data) {
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
}
return str.join("&");
}
}
})
}
}
app.factory("userAccount", ["$resource", "$http", "appSettings", userAccount]);
})();
I've tried to manually use $scope.$apply(), $scope.$digest(), even $timeout(), but none of them are working properly. I either get a $digest is already running error or nothing happens at all.
The only work around I can use is to manually remove the class on the div using jQuery, but that's not the correct way to do it using AngualrJS.
Related
var app = angular.module('part3', []);
app.controller('Part3Controller' ,function ($scope) {
$scope.Message1 = "apek";
$scope.IsLogedIn = false;
$scope.Message = '';
$scope.Submitted = false;
$scope.IsFormValid = false;
$scope.LoginData = {
UserName: '',
Password: ''
};
$scope.$watch('f1.$valid', function (newVal) {
$scope.IsFormValid = newVal;
});
$scope.Login = function () {
$scope.Submitted = true;
if ($scope.IsFormValid) {
alert("eeeeee")
alert("dsds")
serv.GetUser($scope.LoginData).then(function (d) {
alert("dsdsdfsdfs");
if (d.data.UserName != null) {
alert("he;llo1");
$scope.IsLoggedIn = true;
$scope.Message = "Successfully Login" + d.data.FullName;
}
else {
alert("Invalid Credential")
}
})
}
}
})
app.factory('serv', function ($http) {
alert("helloo");
var fac = {};
fac.GetUser = function (d) {
$scope.Submitted = true;
return $http({
url: '/Data/UserLogin',
method: 'POST',
data: JSON.stringify(d),
header: { 'content-type': 'application/json' }
});
};
return fac;
});
I had written above code for login functionality in my app but it is not calling factory "serv" its showing error "angular.min.js:92 ReferenceError: serv is not defined"
"angular.min.js:92 ReferenceError: serv is not defined"
When you want to use a factory or service with a controller in angular, you need to inject them with that. We have:
app.factory('name_of_factory', factory_function);
and controller:
app.controller('name_of_controller', controller_function($scope,factory_name_you_want_to_use) { //blah blah });
That was some of explanation, you just need to inject name of factory with your controller. Your Controller JS will look like this:
app.controller('Part3Controller' ,function ($scope,serv){//yourcode});
need to inject serv factory to the controller
controller('Part3Controller' ,function ($scope,serv) {
I wrote a page that allows me to change my password. The code works and it does everything I want it to do, so I started writing tests. Since I'm not as experienced in Angular testing this had proven to be quite difficult and I can't get passed this error:
TypeError: 'undefined' is not an object (evaluating 'plan.apply')
at /Users/denniegrondelaers/asadventure/myproject-web/src/users/controllers/userPasswordController.js:9
at /Users/denniegrondelaers/asadventure/myproject-web/test/unitTests/specs/users/controllers/userPasswordControllerSpec.js:98
The controller:
userPasswordController.js
users.controllers.controller('userPasswordController',
['$scope', 'Session', '$state', 'UserService', 'languages',
function ($scope, Session, $state, UserService, languages) {
$scope.languages = languages;
$scope.password = "";
$scope.notEqual = false;
$scope.isSuccessful = false;
$scope.changePassword = function() {
var pw = {
userId: Session.getCurrentSession().userId,
oldPassword: encrypt($scope.password.oldPassword),
newPassword: encrypt($scope.password.newPassword),
newPasswordRepeat: encrypt($scope.password.newPasswordRepeat)
};
if (pw.newPassword === pw.newPasswordRepeat) {
$scope.notEqual = false;
UserService.setNewPassword(pw).then(function(res) {
$scope.formErrors = undefined;
$scope.isSuccessful = true;
}, function (error) {
$scope.formErrors = error.data;
}
);
} else {
$scope.notEqual = true;
}
};
var encrypt = function (password) {
var encrypted = CryptoJS.md5(password);
return encrypted.toString(CryptoJS.enc.Hex);
};
}
]
);
The service:
userService.js
userService.setNewPassword = function (password) {
return $http
.put(EnvironmentConfig.endpointUrl +
"/password/change", password)
};
The test:
userPasswordControllerSpec.js
describe('Users', function () {
describe('Controllers', function () {
fdescribe('userPasswordController', function () {
var $scope,
controller,
$q,
willResolve,
mockSession,
mockState,
mockUserService,
mockLanguages;
beforeEach(function () {
module('mysite.users.controllers');
module(function ($provide) {
$provide.value('translateFilter', function (a) {
return a;
});
$provide.value('$state', function (a) {
return a;
});
});
mockSession = {
getCurrentSession: function () {
return {userId: 4};
}
};
mockState = {
params: {
id: 1
},
go: function () {
}
};
mockLanguages = {
getLanguages : function () {
var deferred = $q.defer();
deferred.resolve({
data: [{}]
});
return deferred.promise;
}
};
mockUserService = {
setNewPassword : function () {
var deferred = $q.defer();
if (willResolve) {
deferred.resolve({
data: [{}]
});
}
return deferred.promise;
}
};
inject(function (_$q_, $controller, $rootScope) {
controller = $controller;
$q = _$q_;
$scope = $rootScope.$new();
});
controller('userPasswordController', {$scope: $scope, Session: mockSession, $state: mockState,
UserService: mockUserService, languages: mockLanguages
});
willResolve = true;
});
it('should change password', function () {
spyOn(mockUserService, 'setNewPassword').and.callThrough();
spyOn(mockState, 'go').and.callThrough();
spyOn(mockSession, 'getCurrentSession').and.callFake();
expect(mockUserService.setNewPassword).not.toHaveBeenCalled();
expect($scope.isSubmitable()).not.toBeTruthy();
$scope.compareStoreSelection = function () {
return true;
};
$scope.password = {
oldPassword: "123456",
newPassword: "password",
newPasswordRepeat: "password"
};
expect($scope.isSubmitable()).toBeTruthy();
>>> $scope.changePassword(); <<< LOCATION OF ERROR, line 98
expect(mockUserService.setNewPassword).toHaveBeenCalled();
$scope.$apply();
});
});
});
});
I've marked the line that gives the code in the test.
Anybody any idea how to fix this? A colleague suggested altering my controller code, but I'd like to keep it as it is, since it seems logical that this code shouldn't be altered for testing to work, right?
Solution
Yarons' suggestion to change the mockSession.getCurrentSession.callFake to mockSession.getCurrentSession.callThrough fixed it!
I have a controller which has a function to get some alerts from an API and update a count on the front-end of my site which is bound to the alert.
Unfortunately the ng-bind attribute I'm using doesn't seem to be updating the count live, even though a simple console.log() is telling me that the actual alert count is being updated in the controller.
Front-end
<div class="modeSelector modeSelector_oneUp" data-ng-controller="MyLivestockController as vm">
<a class="modeSelector-mode" data-ui-sref="my-livestock">
<div class="modeSelector-type">Alerts</div>
<img class="modeSelector-icon" src="/inc/img/_icons/envelope-black.svg" onerror="this.src=envelope-black.png" />
<span data-ng-bind="vm.alertCount"></span>
</a>
</div>
Controller
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
angular
.module('abp')
.controller('MyLivestockController', MyLivestockController);
})();
Service
(function() {
'use strict';
function userService($q, $sessionStorage, $localStorage, $filter, user) {
var service = this;
service.getAlerts = function(id) {
var deferred = $q.defer();
user.alerts({ userID: id }, function(response) {
if (response.hasOwnProperty('data')) {
// Convert dates to valid Date
angular.forEach(response.data, function(alert) {
/* jshint camelcase: false */
if (alert.created_at) {
alert.created_at = $filter('abpDate')(alert.created_at);
/* jshint camelcase: true */
}
});
deferred.resolve(response.data);
}
else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
angular
.module('abp')
.service('userService', userService);
})();
As you can see, I've got my getAlerts() function being called every time an alert is deleted, using the deleteAlert() function, but the <span data-ng-bind="vm.alertCount"></span> on the front-end only updates after refreshing the page, where I'd like it to update live.
Your bind is not updating because you change the value of alertCount outside of digest cycle of your angular app. When you refresh your app, the digest runs and thus your value gets updated. Wrap the update of the variable in $scope.apply() like so:
$scope.$apply(function(){
vm.alertCount = alertData.length;
});
This will force digest and update the value live.
If you have more values that are updated outside of digest (any callback, promise etc) you can force digest cycle by calling:
$scope.$apply();
Hope it helps.
EDIT -----
Given your update with full code, I see that you are not injecting scope anywhere in your controller, the controllers I write usually start like that:
(function () {
var app = angular.module('mainModule');
app.controller('myController', ['$scope', '$myService', function ($scope, $myService) {
//logic
}]);
}());
EDIT -----
Here is a quick go I had on your code:
(function() {
'use strict';
var app = angular.module('abp');
app.controller('MyLivestockController', ['$scope', 'userService', function($scope, userService) {
var vm = {};
$scope.vm = vm;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id);
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
userService.getAlerts(id).then(function(alertData) {
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
//important, this is promise so we have to apply the scope to update view
$scope.$apply();
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}]);
})();
The general idea is:
you create an app (angular.module)
you create a controller in this app, with $scope injected
any values you want to be updated on your view, you add to $scope
if you have any $scope updates in a callback, event or promise, you wrap them in (or follow with) $scope.$apply call
I think this should work for you :)
I have attempted to reproduce your code below with a mock userService, and some slight modifications to the html view so we can more clearly see the alerts and delete them. I have not modified your Controller.
This appears to work, yes?
Which leads me to believe there may be some issue with the implementation of your userService. If you are able to post the relevant code, I can update this answer with a clarified solution.
UPDATE: As you've updated your question with the userService code, I've updated the below to more closely match. I still have a mock service standing in place of the user dependency of the userService. Additionally I made a couple of small edits to the Controller class so that while promises are still resolving we can see 'Updating...' in place of the alerts count.
This all still appears to work, unless I'm misunderstanding - will think on it more and update this 'answer' when I can think of where else to investigate for the source of the issue, see if we can at least reproduce it!
(function() {
'use strict';
function MyLivestockController(userService) {
var vm = this;
vm.myLivestockNotification = {
isLoading: true,
hasError: false
};
vm.alertsNotification = {
isLoading: true,
hasError: false,
hasData: false
};
vm.deleteAlert = function(id) {
vm.currentAlert = void 0;
vm.alertsNotification.isLoading = true;
return userService.deleteAlert(vm.user.id, id).then(function() {
// Remove the alert from our Array
vm.alerts = vm.alerts.filter(function(alert) {
return alert.id !== id;
});
// Refresh the alert count for the user
vm.getAlerts(vm.user.id).then(function() {
vm.alertsNotification.isLoading = false; //put here, loading isn't really finished until after .getAlerts() is done
vm.alertsNotification.hasError = false;
});
}, function() {
vm.alertsNotification.hasError = true;
});
};
vm.getAlerts = function(id) {
vm.alertsNotification.isLoading = true;
return userService.getAlerts(id).then(function(alertData) { //return the promise so we can chain .then in .deleteAlert()
vm.alertCount = alertData.length;
if (vm.alertCount > 0) {
vm.alertsNotification.hasData = true;
} else {
vm.alertsNotification.hasData = false;
}
vm.alerts = alertData;
vm.alertsNotification.isLoading = false;
vm.alertsNotification.hasError = false;
}, function() {
vm.alertsNotification.hasError = true;
});
};
// Init
(function() {
userService.getCurrentUser().then(function(data) {
vm.myLivestockNotification.hasError = false;
vm.myLivestockNotification.isLoading = false;
vm.user = data;
// Get alert count for the user
vm.getAlerts(vm.user.id);
}, function() {
vm.myLivestockNotification.hasError = true;
});
})();
}
function userMock($q, $timeout, $log) {
var _alerts = {
data: [{
id: 1,
message: "He doesn't sleep, he waits..."
}, {
id: 2,
message: "He doesn't mow his lawn, he stands outside and dares it to grow."
}, {
id: 3,
message: "Some magicians can walk on water. He can swim through land."
}]
},
_currentUser = {
id: 'Q2h1Y2sgTm9ycmlz'
};
return {
getCurrentUser: function getCurrentUser() {
$log.log("getCurrentUser");
//return $q.when(_currentUser);
return $timeout(function() { //use $timeout to simulate some REST API latency...
return _currentUser;
}, 500);
},
getAlerts: function getAlerts(id) {
$log.log("getAlerts: " + id); //not doing anything with the id in this mock...
$log.log(_alerts.data);
//return $q.when(_alerts);
return $timeout(function() {
return _alerts;
}, 500);
},
deleteAlert: function deleteAlert(userId, id) {
$log.log("deleteAlert: " + userId + " :: " + id);
//return $q.when(_alerts);
return $timeout(function() {
for (var i = 0; i < _alerts.data.length; i++) {
if (_alerts.data[i].id === id) {
_alerts.data.splice(i, 1);
$log.log("alert found and deleted");
break;
}
}
$log.log(_alerts.data);
return _alerts;
}, 500);
}
};
}
function userService($q, $timeout, $log, userMock) {
var service = this;
service.getCurrentUser = userMock.getCurrentUser;
service.getAlerts = function(id) {
var deferred = $q.defer();
userMock.getAlerts(id).then(function(response) {
if (response.hasOwnProperty('data')) {
// Convert 'he' to 'Chuck Norris'
angular.forEach(response.data, function(alert) {
if (alert.message) {
alert.message = alert.message.replace(/he/gi, "Chuck Norris");
}
});
deferred.resolve(response.data);
} else {
deferred.reject('DATA ERROR');
}
}, function(e) {
deferred.reject(e);
});
return deferred.promise;
};
service.deleteAlert = function(userId, id) {
var deferred = $q.defer();
userMock.deleteAlert(userId, id).then(function(response) {
deferred.resolve(response.data);
}, function(e) {
deferred.reject('DATA ERROR');
});
return deferred.promise;
};
return service;
};
angular
.module('abp', [])
.service('userMock', userMock)
.service('userService', userService)
.controller('MyLivestockController', MyLivestockController);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<div ng-app="abp">
<div data-ng-controller="MyLivestockController as vm">
<div>Alerts</div>
<span data-ng-bind="vm.alertsNotification.isLoading ? 'Updating...' : vm.alertCount"></span>
<div data-ng-repeat="alert in vm.alerts">
{{alert.id}}: {{alert.message}}
<button ng-click="vm.deleteAlert(alert.id)">Delete</button>
</div>
</div>
</div>
I am looking to run the following controller but im having trouble with scope.
I have a service that calls two functions that retrieve meta data to populate scope variables.
The issue is that using the service to call back the data interferes with other actions happening in the code. I have a directive on a tag that shows/hides an error on the span element once the rule is validated. This is now not functioning correctly. I run the code without asynchronous functions then everything works correctly.
My Plunker code is here
and the plunker of the desired behaviour is here
Plunker working example without dynamic data loading
<form class="form-horizontal">
<div class="control-group" ng-repeat="field in viewModel.Fields">
<label class="control-label">{{field.label}}</label>
<div class="controls">
<input type="text" id="{{field.Name}}" ng-model="field.data" validator="viewModel.validator" ruleSetName="{{field.ruleSet}}"/>
<span validation-Message-For="{{field.Name}}"></span>
</div>
</div>
<button ng-click="save()">Submit</button>
</form>
How do I get all bindings to update so everything is sync and loaded correctly?
angular.module('dataApp', ['servicesModule', 'directivesModule'])
.controller('dataCtrl', ['$scope', 'ProcessService', 'ValidationRuleFactory', 'Validator',
function($scope, ValidationRuleFactory, Validator, ProcessService) {
$scope.viewModel = {};
var FormFields = {};
// we would get this from the meta api
ProcessService.getProcessMetaData().then(function(data) {
alert("here");
FormFields = {
Name: "Course",
Fields: [{
type: "text",
Name: "name",
label: "Name",
data: "",
required: true,
ruleSet: "personFirstNameRules"
}, {
type: "text",
Name: "description",
label: "Description",
data: "",
required: true,
ruleSet: "personEmailRules"
}]
};
$scope.viewModel.Fields = FormFields;
ProcessService.getProcessRuleData().then(function(data) {
var genericErrorMessages = {
required: 'Required',
minlength: 'value length must be at least %s characters',
maxlength: 'value length must be less than %s characters'
};
var rules = new ValidationRuleFactory(genericErrorMessages);
$scope.viewModel.validationRules = {
personFirstNameRules: [rules.isRequired(), rules.minLength(3)],
personEmailRules: [rules.isRequired(), rules.minLength(3), rules.maxLength(7)]
};
$scope.viewModel.validator = new Validator($scope.viewModel.validationRules);
});
});
var getRuleSetValuesMap = function() {
return {
personFirstNameRules: $scope.viewModel.Fields[0].data,
personEmailRules: $scope.viewModel.Fields[1].data
};
};
$scope.save = function() {
$scope.viewModel.validator.validateAllRules(getRuleSetValuesMap());
if ($scope.viewModel.validator.hasErrors()) {
$scope.viewModel.validator.triggerValidationChanged();
return;
} else {
alert('person saved in!');
}
};
}
]);
The validation message directive is here
(function(angular, $) {
angular.module('directivesModule')
.directive('validationMessageFor', [function() {
return {
restrict: 'A',
scope: {eID: '#val'},
link: function(scope, element, attributes) {
//var errorElementId = attributes.validationMessageFor;
attributes.$observe('validationMessageFor', function(value) {
errorElementId = value;
//alert("called");
if (!errorElementId) {
return;
}
var areCustomErrorsWatched = false;
var watchRuleChange = function(validationInfo, rule) {
scope.$watch(function() {
return validationInfo.validator.ruleSetHasErrors(validationInfo.ruleSetName, rule.errorCode);
}, showErrorInfoIfNeeded);
};
var watchCustomErrors = function(validationInfo) {
if (!areCustomErrorsWatched && validationInfo && validationInfo.validator) {
areCustomErrorsWatched = true;
var validator = validationInfo.validator;
var rules = validator.validationRules[validationInfo.ruleSetName];
for (var i = 0; i < rules.length; i++) {
watchRuleChange(validationInfo, rules[i]);
}
}
};
// get element for which we are showing error information by id
var errorElement = $("#" + errorElementId);
var errorElementController = angular.element(errorElement).controller('ngModel');
var validatorsController = angular.element(errorElement).controller('validator');
var getValidationInfo = function() {
return validatorsController && validatorsController.validationInfoIsDefined() ? validatorsController.validationInfo : null;
};
var validationChanged = false;
var subscribeToValidationChanged = function() {
if (validatorsController.validationInfoIsDefined()) {
validatorsController.validationInfo.validator.watchValidationChanged(function() {
validationChanged = true;
showErrorInfoIfNeeded();
});
// setup a watch on rule errors if it's not already set
watchCustomErrors(validatorsController.validationInfo);
}
};
var getErrorMessage = function(value) {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return '';
}
var errorMessage = "";
var errors = validationInfo.validator.errors[validationInfo.ruleSetName];
var rules = validationInfo.validator.validationRules[validationInfo.ruleSetName];
for (var errorCode in errors) {
if (errors[errorCode]) {
var errorCodeRule = _.findWhere(rules, {errorCode: errorCode});
if (errorCodeRule) {
errorMessage += errorCodeRule.validate(value).errorMessage;
break;
}
}
}
return errorMessage;
};
var showErrorInfoIfNeeded = function() {
var validationInfo = getValidationInfo();
if (!validationInfo) {
return;
}
var needsAttention = validatorsController.ruleSetHasErrors() && (errorElementController && errorElementController.$dirty || validationChanged);
if (needsAttention) {
// compose and show error message
var errorMessage = getErrorMessage(element.val());
// set and show error message
element.text(errorMessage);
element.show();
} else {
element.hide();
}
};
subscribeToValidationChanged();
if (errorElementController)
{
scope.$watch(function() {
return errorElementController.$dirty;
}, showErrorInfoIfNeeded);
}
scope.$watch(function() {
return validatorsController.validationInfoIsDefined();
}, subscribeToValidationChanged());
});
}
};
}]);
})(angular, $);
I'm having an odd issue in AngularJS where MainCtrl isn't fire at all. I go to localhost/ and it redirects to localhost/#/ but the page is blank. There are no errors/messages in console. I can confirm that /views/main.html is publicly accessible. I don't know why this isn't working. Am I missing anything?
angular.module('TurkApp', ['ngCookies']).config([
'$routeProvider',
function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: '/views/main.html',
controller: 'MainCtrl'
}).otherwise({ redirectTo: '/' });
}
]);
angular.module('TurkApp', []).controller('MainCtrl', [
'$scope',
'$http',
'$location',
'$cookies',
function ($scope, $http, $location, $cookies) {
$scope.questionIsLoading = true;
$scope.answerButtonsDisabled = true;
$scope.showHelp = false;
$scope.currentRetries = 0;
$scope.acceptedHit;
$scope.currentQuestionText = null;
$scope.currentQuestionID = null;
var AssignmentID, Interest;
var getInterest = function () {
return $cookies.interest;
};
var getAssignmentID = function () {
var qsRegex = new RegExp('(?:\\?|&)AssignmentID=(.*?)(?=&|$)', 'gi'), m, assignmentID = false;
while ((match = qsRegex.exec(document.location.search)) != null) {
assignmentID = match[1];
}
if (!assignmentID) {
assignmentID = $location.search()['AssignmentID'];
}
$scope.acceptedHit = assignmentID == 'ASSIGNMENT_ID_NOT_AVAILABLE' || !assignmentID ? false : true;
return assignmentID;
};
$scope.loadNextQuestion = function () {
$scope.questionIsLoading = $scope.answerButtonsDisabled = true;
$http.get('/workers/' + Interest + '/next-question').success(function (data, status) {
$scope.currentQuestionText = data.text;
$scope.currentQuestionID = data.id;
$scope.questionIsLoading = $scope.answerButtonsDisabled = false;
}).error(function () {
console.log('Answer send failed');
});
};
$scope.sendAnswer = function (answer) {
if (!$scope.questionIsLoading && !$scope.answerButtonsDisabled) {
$scope.questionIsLoading = $scope.answerButtonsDisabled = true;
$http.post('/workers/' + Interest + '/answer-question', {
question_id: $scope.currentQuestionID,
question_text: $scope.currentQuestionText,
answer: answer
}).success(function (data, status) {
$scope.loadNextQuestion();
}).error(function () {
console.log('Answer send failed');
});
}
};
$scope.toggleHelp = function () {
$scope.showHelp = $scope.showHelp ? false : true;
};
var init = function () {
AssignmentID = getAssignmentID();
Interest = getInterest();
$scope.loadNextQuestion();
};
init();
}
]);
You are creating the module 'TurkApp' twice, thereby losing the configuration registered with the first module:
angular.module('TurkApp', ['ngCookies'])
When you include the second parameter to the angular.module function, it creates the module. If you omit the second parameter, it assumes the modules exists and "extends" it.
Change:
angular.module('TurkApp', [])
to:
angular.module('TurkApp')
See the usage section here - http://docs.angularjs.org/api/angular.module