Argument '*' is not a function on AngularJS - javascript

Adding ng-controller on view causing Error: [ng:areq] Argument 'ValidationCtrl' is not a function, got undefined. Following are the code snippets:
profile.html
<div class="row" ng-controller="ValidationCtrl">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" placeholder="Enter your first name" class="form-control" name="firstname" ng-model="user.first_name">
<span class="error text-small block" ng-if="Form.first_name.$dirty && Form.first_name.$invalid">Last Name is required</span>
<span class="success text-small" ng-if="Form.first_name.$valid">Wonderful!</span>
</div>
</div>
</div>
app.js
var myApp = angular.module("MyApp",['ngResource','ngRoute','ui.router','ngMessages','ngResource','cfp.loadingBar','duScroll','ngAnimate','satellizer','pascalprecht.translate','ngCookies','oc.lazyLoad','ui.bootstrap','toastr'])
.config(['$stateProvider', '$urlRouterProvider','$authProvider','$ocLazyLoadProvider','JS_REQUIRES',function($stateProvider, $urlRouterProvider,$authProvider,$ocLazyLoadProvider,jsRequires){
$stateProvider
.state('app.profile', {
url: '/profile',
templateUrl: "views/profile.html",
title: 'Buttons',
resolve: loadSequence('flow','validationCtrl')
});
$ocLazyLoadProvider.config({
debug: false,
events: true,
modules: jsRequires.modules
});
function loadSequence() {
var _args = arguments;
return {
deps: ['$ocLazyLoad', '$q',
function ($ocLL, $q) {
var promise = $q.when(1);
for (var i = 0, len = _args.length; i < len; i++) {
promise = promiseThen(_args[i]);
}
return promise;
function promiseThen(_arg) {
if (typeof _arg == 'function')
return promise.then(_arg);
else
return promise.then(function () {
var nowLoad = requiredData(_arg);
if (!nowLoad)
return $.error('Route resolve: Bad resource name [' + _arg + ']');
return $ocLL.load(nowLoad);
});
}
function requiredData(name) {
if (jsRequires.modules)
for (var m in jsRequires.modules)
if (jsRequires.modules[m].name && jsRequires.modules[m].name === name)
return jsRequires.modules[m];
return jsRequires.scripts && jsRequires.scripts[name];
}
}]
};
}
}]);
validationCtrl.js
'use strict';
/**
* controller for Validation Form example
*/
myApp.controller('ValidationCtrl', ["$scope", "$state", "$timeout", "SweetAlert", function ($scope, $state, $timeout, SweetAlert) {
alert('validation');
$scope.master = $scope.myModel;
$scope.form = {
submit: function (form) {
var firstError = null;
if (form.$invalid) {
var field = null, firstError = null;
for (field in form) {
if (field[0] != '$') {
if (firstError === null && !form[field].$valid) {
firstError = form[field].$name;
}
if (form[field].$pristine) {
form[field].$dirty = true;
}
}
}
angular.element('.ng-invalid[name=' + firstError + ']').focus();
SweetAlert.swal("The form cannot be submitted because it contains validation errors!", "Errors are marked with a red, dashed border!", "error");
return;
} else {
SweetAlert.swal("Good job!", "Your form is ready to be submitted!", "success");
//your code for submit
}
},
reset: function (form) {
$scope.myModel = angular.copy($scope.master);
form.$setPristine(true);
}
};
}]);
and my config.constant.js
myApp.constant('JS_REQUIRES', {
scripts: {
'validationCtrl': ['controllers/validationCtrl.js']
}});
Thanks!

Related

Changed email address will not be forwarded from one to the other in AngularJS

I have a form, where an email address is "saved":
It derives from the following code:
'use strict';
angular.module('app').factory('Emails', function ($window)
{
var DEFAULT = 'change-it#something.com';
var data = $window.eval($window.localStorage.getItem('emailaddress')) || DEFAULT;
var Emails = {};
Emails.get = function ()
{
return data;
};
Emails.set = function (emailaddress)
{
data = emailaddress;
$window.localStorage.setItem('emailaddress', $window.JSON.stringify(data));
};
return Emails;
});
When clicking on the button for the email address a new form opens:
The code for this popup (email-popup.html) is the following:
<p>Email-Adresse eingeben</p>
<form name="emailForm">
<div class="rules__popup">
<input type="email" name="input" ng-model="emailaddress" min="1" maxlength="30"
ng-change="updateEmail" required ng-keypress="positiveInteger($event)" ng-controller="PdfsmtpCtrl">
</div>
</form>
But when changing the email address herein and clicking the "OK-button" on top right, nothing happens. The email address remains the same!
To be complete, here is the code, where all starts and ends:
use strict';
angular.module('app')
.controller('PdfsmtpCtrl', function ($scope, Pdfsmtp, Emails, $ionicPopup, $window)
{
$scope.emailaddress = Emails.get();
$scope.changeEmail = function (emailaddress)
{
//var regex = /^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
var popupScope = $scope.$new();
popupScope.emailForm
{
name: $scope.emailaddress
};
$ionicPopup.prompt
({
cssClass: 'rules__popup',
templateUrl: 'pdfsmtp/email-popup.html',
scope: $scope,
buttons:
[
{
text: 'OK',
type: 'button-balanced',
onTap: function (e)
{
//if (isNaN($scope.emails[email]))
if ($scope.emailaddress === undefined && isNaN($scope.emailaddress))
{
$scope.$emit('toast', 'Keine gültige Email-Adresse!');
e.preventDefault();
$scope.emailaddress = "change-it#something.com";
}
else if (!$scope.emailaddress.match(regex))
{
$scope.$emit('toast', 'Keine gültige Email-Adresse!');
e.preventDefault();
$scope.emailaddress = "change-it#something.com";
}
}
}
]
}).then(function ()
{
if ($window.cordova && $window.cordova.plugins.Keyboard)
{
$window.cordova.plugins.Keyboard.close();
}
});
};
$scope.save = function ()
{
Emails.set($scope.emailaddress);
$scope.emailsModal.hide();
};
What is going wrong here?

modalinstance inject view model to update

I am using Modal popups to list out accounts details (accno and name). once row is selected from list view model variable(vm.vismaDebitAccount) need to update which is dynamic. In actual scenario popup will be open on textbox onclick and once row is selected from popup relevant textbox text should be update with account name. The view model variable(a particular textbox binding) should be able to inject to modalinstance result without hard cord things.
Here is my code.
my problem is why vm.vismaDebitAccount is not getting update? Please help me.
Here is the place on UI binding
<tr ng-repeat="accEntry in vm.vismaAccEntries">
<td>{{accEntry.invoiceNo}}</td>
<td><input type="text" ng-model='accEntry.debitAccNo' required name="field" ng-click="vm.openVismaAccModal('debit')" /></td>
<td><input type="text" ng-model='accEntry.debitVat' required name="field" /></td>
<td><input type="text" ng-model='accEntry.creditAccNo' required name="field" ng-click="vm.openVismaAccModal('credit')"/></td>
<td><input type="text" ng-model='accEntry.creditVat' required name="field" /></td>
<td>{{accEntry.amount}}</td>
<td>{{accEntry.voucherDate}}</td>
<td>{{accEntry.dueDate}}</td>
app.controller('invoiceCodeController', ['$routeParams', 'invoiceService', 'vismaService', '$uibModal', '$log', function ($routeParams, invoiceService, vismaService, $uibModal, $log) {
var vm = this;
var vismaDebitAccount = {
catogory: '',
account: ''
}
var vismaCreditAccount = {
catogory: '',
account: ''
}
vm.openVismaAccModal = function (accountType) {
console.log('hi before')
var modalInstance = $uibModal.open({
templateUrl: 'accountPopup.html',
controller: 'vismaAccController as vm'
});
modalInstance.result.then(function (selectedAccount) {
if (accountType === 'debit') {
vm.vismaAccEntries[0].debitAccNo = selectedAccount.account.No;
}
if (accountType === 'credit') {
vm.vismaAccEntries[0].creditAccNo = selectedAccount.account.No;
}
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
}]);
app.controller('vismaAccController', ['vismaService', '$uibModalInstance', function (vismaService, $uibModalInstance) {
var vm = this;
var selectedAcc = {
category: '',
account: ''
};
Init();
function Init() {
getVismaAccData();
}
vm.tabChange = function (e) {
if (e.target.nodeName === 'A') {
e.preventDefault();
}
}
vm.rowSelect = function (index, debitAcc, flag) {
selectedAcc.category = flag;
selectedAcc.account = debitAcc;
}
vm.ok = function () {
$uibModalInstance.close(selectedAcc);
};
vm.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
function getVismaAccData() {
var errors = [];
vismaService.getSuppliers().then(function (data) {
vm.vismaSuppliers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getCustomers()
.then(function (data) {
vm.vismaCustomers = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
vismaService.getGeneralLedger()
.then(function (data) {
vm.vismaGL = data;
},
function (errorMsg) {
errors.push('<li>' + errorMsg + '</li>');
vm.savedSuccessfully = false;
});
if (errors.length > 0) {
vm.message = errors.join(' ');
}
}
}]);

Angular - getting value from directive in the controller

I need to pass a selected value from a directive that I am using in several places. It is a select input field that I need to get a selected value from.
This is how the directive looks like:
angular.module('quiz.directives')
.directive('fancySelect', function($rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: 'templates/directives/fancySelect.html',
scope: {
title: '#',
model: '=',
options: '=',
multiple: '=',
enable: '=',
onChange: '&',
class: '#'
},
link: function(scope) {
scope.showOptions = false;
scope.displayValues = [];
scope.$watch('enable', function(enable) {
if (!enable && scope.showOptions) {
scope.toggleShowOptions(false);
}
});
scope.toggleShowOptions = function(show) {
if (!scope.enable) {
return;
}
if (show === undefined) {
show = !scope.showOptions;
}
if (show) {
$rootScope.$broadcast('fancySelect:hideAll');
}
$timeout(function() {
scope.showOptions = show;
});
};
scope.toggleValue = function(value) {
if (!value) {
return;
}
if (!scope.multiple) {
scope.model = value;
console.log(scope.model);
return;
}
var index = scope.model.indexOf(value);
if (index >= 0) {
scope.model.splice(index, 1);
}
else {
scope.model.push(value);
}
if (scope.onChange) {
scope.onChange();
}
};
scope.getDisplayValues = function() {
if (!scope.options || !scope.model) {
return [];
}
if (!scope.multiple && scope.model) {
return scope.options.filter(function(opt) {
return opt.id == scope.model;
});
}
return scope.options.filter(function(opt) {
return scope.model.indexOf(opt.id) >= 0;
});
};
$rootScope.$on('fancySelect:hideAll', function() {
scope.showOptions = false;
});
}
};
});
When I do console.log(scope.model); I get the selected value, but I am not sure how to get it and use it in my controller?
This is the controller:
angular.module('quiz.controllers')
.controller('ProfileController', function(
$scope,
$state,
$stateParams,
UserService,
$auth,
MessageService,
$ionicLoading,
AppSettings,
$timeout,
AvatarService,
PushService,
$http
) {
$scope.user = UserService.get();
$scope.profilePromise = {};
if ($scope.user.player.avatar == ""){
$scope.user.player.avatar = AvatarService.getRandom();
}
$http.get(AppSettings.apiUrl + '/years')
.then(function(result) {
$scope.years = result.data;
});
$scope.updateUser = function(form) {
if (!form.$valid) {
var message = "Ugyldig data i skjema. Sjekk felter markert med rødt.";
MessageService.alertMessage(message);
return;
}
saveUser($scope.user);
};
$scope.getNextAvatar = function() {
$scope.user.player.avatar = AvatarService.getNext($scope.user.player.avatar);
};
$scope.getPreviousAvatar = function() {
$scope.user.player.avatar = AvatarService.getPrevious($scope.user.player.avatar);
};
var saveUser = function(user) {
$scope.profilePromise = UserService.save(user);
$scope.profilePromise.then(function(result) {
$scope.user = result.data.user;
PushService.init();
PushService.getDeviceId().then(function(id) {
UserService.addDevice(id);
});
if ($stateParams.register) {
$state.go('main.front');
}
}, function(error) {
var message = "Kunne ikke lagre bruker. Melding fra server: " + error.data.message;
MessageService.alertMessage(message);
});
};
});
You already have an onChange binding in the scope, so why don't you use that one?
In your directive:
if (scope.onChange) {
scope.onChange({ $value: scope.model });
}
Then pass a controller function to your directive:
<fancy-select on-change="onChange($value)"></fancy-select>
In your controller:
$scope.onChange = function(val) {
// do something with the value
}

AngularJS migration from v1.1.5 to v1.5.8 Argument 'Login.Controller' is not a function, got undefined

I am trying to migrate an angularJS from version 1.1.5 to the latest 1.5.8 but I am getting this error:
angular.js:13920 Error: [ng:areq] Argument 'Login.Controller' is not a function, got undefined
http://errors.angularjs.org/1.5.8/ng/areq?p0=Login.Controller&p1=not%20a%20function%2C%20got%20undefined
js
var app = {};
app = angular.module('myApp', ['ngResource', 'ngRoute'])
//Login Controller
Login = {
/**
* Initializes the login page.
*/
controller: function ($scope, $location, User) {
Login.initializeScopeVariables($scope);
Login.createScopeFunctions($scope, $location, User);
},
initializeScopeVariables: function ($scope) {
$scope.$root.forgotPasswordUsername = null;
},
createScopeFunctions: function ($scope, $location, User) {
$scope.reset = function () {
$scope.$root.filters = {};
Login.resetForm($scope);
}
$scope.submit = function () {
Login.submitForm($scope, $location, User);
}
$scope.validate = function () {
if ($scope.loginForm.$valid) {
$('#submit-btn').linkbutton('enable');
} else {
$('#submit-btn').linkbutton('disable');
}
}
$scope.$root.submitPasswordReminder = function () {
if ($scope.$root.forgotPasswordUsername) {
mask(true);
User.sendPasswordReminder($scope.$root.forgotPasswordUsername).success(
function (data) {
mask(false);
if (data.status == M2M.Response.ERROR) {
error(data.statusMessage);
} else {
info(Locale.get('passwordReminderSent'));
$scope.clearPasswordReminderForm();
}
}
).error(errorCallback);
}
}
$scope.$root.clearPasswordReminderForm = function () {
$('#forgot-password-window').window('close');
$scope.$root.forgotPasswordUsername = null;
}
$(document).keypress(function (event) {
if (13 == event.keyCode) {
$scope.submit();
$scope.$apply();
}
if (27 == event.keyCode) {
$scope.reset();
$scope.$apply();
}
})
},
/**
* Resets login form
*
* #param $scope
*/
resetForm: function ($scope) {
$scope.username = '';
$scope.password = '';
$('input').removeClass('validatebox-invalid');
},
/**
* Submits login form
*
* #param $scope
* #param $location
* #param User
*/
submitForm: function ($scope, $location, User) {
if (!($scope.username && $scope.password)) {
return;
}
mask(true);
User.authenticate($scope.username, $scope.password).success(
function (data) {
if (data.status == M2M.Response.ERROR) {
mask(false);
error(data.statusMessage);
} else {
location.href = 'main.html';
}
}
).error(errorCallback);
}
}
html
<div class="login-area" ng-controller="Login.controller" style="width: 1300px; margin: auto">
<form autocomplete="off">
<div class="login-panel" ng-form name="loginForm" align="center">
<table>
<tr>
<td><fmt:message key="username"/></td>
<td>
<input class="easyui-validatebox w140" type="text" name="username"
data-options="required:true"
ng-model="username"
ng-change="validate()"
required/>
</td>
</tr>
<tr>
<td><fmt:message key="password"/></td>
<td><input class="easyui-validatebox w140" type="password" name="password"
data-options="required:true"
ng-model="password"
autocomplete="off"
ng-change="validate()"
required/></td>
</tr>
<tr>
<td colspan="2">
<a id="submit-btn" class="easyui-linkbutton" data-options="iconCls:'icon-ok',disabled: true"
ng-click="submit()"><fmt:message key="submit"/></a>
<a id="reset-btn" class="easyui-linkbutton" data-options="iconCls:'icon-undo'"
ng-click="reset()"><fmt:message key="reset"/></a></td>
</tr>
</table>
<div class="clr tac small">
<a href="#" id="forgot-passwd" onclick="$('#forgot-password-window').window('open')"><fmt:message
key="login.forgotPassword"/></a>
</div>
<br>
<div class="clr tac">
<fmt:message key="login.disclaimer"/>
</div>
</div>
</form>
</div>
I can not figure out why this is happening in angular's latest version.
Do I need to make changes in the code?
this is how you define a controller. please refer to this Angular Documentation.
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Angular needs to know which..err..component is a service, which a factory, which a controller etc. so you register it with your module like yourApp.controller.
in the example above, GreetingController will be the name of the controller. so in your case, it'll become loginController. you define all the functionality in the callback function.
function($scope,..){
//code goes here.
}
where ... are other dependencies.
var app = {};
app = angular.module('myApp', ['ngResource', 'ngRoute'])
//Login Controller
app.Controller('LoginController', '$scope', '$location', 'User' function($scope, $location, User){
$scope.initializeScopeVariables();
$scope.createScopeFunctions();
$scope.initializeScopeVariables= function () {
$scope.$root.forgotPasswordUsername = null;
}
$scope.createScopeFunctions= function () {
$scope.reset = function () {
$scope.$root.filters = {};
$scope.resetForm();
}
$scope.submit = function () {
$scope.submitForm();
}
$scope.validate = function () {
if ($scope.loginForm.$valid) {
$('#submit-btn').linkbutton('enable');
} else {
$('#submit-btn').linkbutton('disable');
}
}
$scope.$root.submitPasswordReminder = function () {
if ($scope.$root.forgotPasswordUsername) {
mask(true);
User.sendPasswordReminder($scope.$root.forgotPasswordUsername).success(
function (data) {
mask(false);
if (data.status == M2M.Response.ERROR) {
error(data.statusMessage);
} else {
info(Locale.get('passwordReminderSent'));
$scope.clearPasswordReminderForm();
}
}
).error(errorCallback);
}
}
$scope.$root.clearPasswordReminderForm = function () {
$('#forgot-password-window').window('close');
$scope.$root.forgotPasswordUsername = null;
}
/**
* Resets login form
*
* #param $scope
*/
$scope.resetForm= function () {
$scope.username = '';
$scope.password = '';
$('input').removeClass('validatebox-invalid');
},
/**
* Submits login form
*
* #param $scope
* #param $location
* #param User
*/
$scope.submitForm= function () {
if (!($scope.username && $scope.password)) {
return;
}
mask(true);
User.authenticate($scope.username, $scope.password).success(
function (data) {
if (data.status == M2M.Response.ERROR) {
mask(false);
error(data.statusMessage);
} else {
location.href = 'main.html';
}
}
).error(errorCallback);
}
}
});
$(document).keypress(function (event) {
if (13 == event.keyCode) {
$scope.submit();
$scope.$apply();
}
if (27 == event.keyCode) {
$scope.reset();
$scope.$apply();
}
})
i'm hoping it would work, it's just adjusting your own code according to angular 1.5.x. so, let me know if you get any error.

Controller not firing in AngularJS

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

Categories