Angularjs property undefined in controller - angularjs

Trying to reset password through email. After clicking reset link in email and directed to reset page, console is able to output the "$scope.username" value, however right next line it throws error as "username" not defined. Error Screenshot
Not sure where went wrong. Thanks.
.controller('resetCtrl', function(User, $routeParams, $scope, $timeout, $location) {
app = this;
app.hide = true;
User.resetUser($routeParams.token).then(function(data) {
if (data.data.success) {
app.hide = false;
app.successMsg = 'Please enter a new password';
$scope.username = data.data.user.username;
} else {
app.errorMsg = data.data.message;
}
});
app.savePassword = function(regData, valid, confirmed) {
app.errorMsg = false;
app.disabled = true;
app.loading = true;
console.log($scope.username); // test output
app.regData.username = $scope.username;
User.savePassword(app.regData).then(function(data) {
app.loading = false;
if (data.data.success) {
app.successMsg = data.data.message + '...Redirecting';
$timeout(function() {
$location.path('/login');
}, 2000);
} else {
app.disabled = false;
app.errorMsg = data.data.message;
}
});
}
});

Declare $scope.username outside, that will solve your problem, since you are using controller as syntax, it is better to have it as app.username.
.controller('resetCtrl', function(User, $routeParams, $scope, $timeout, $location) {
app = this;
app.hide = true;
app.username = '';
User.resetUser($routeParams.token).then(function(data) {
if (data.data.success) {
app.hide = false;
app.successMsg = 'Please enter a new password';
app.username = data.data.user.username;
} else {
app.errorMsg = data.data.message;
}
});
app.savePassword = function(regData, valid, confirmed) {
app.errorMsg = false;
app.disabled = true;
app.loading = true;
app.regData.username = app.username;
User.savePassword(app.regData).then(function(data) {
app.loading = false;
if (data.data.success) {
app.successMsg = data.data.message + '...Redirecting';
$timeout(function() {
$location.path('/login');
}, 2000);
} else {
app.disabled = false;
app.errorMsg = data.data.message;
}
});
}
});

Related

Angularjs ticker throwing error as shift() is not a function

I am trying to ticker in AngularJs, I am getting error as
shift() is not a function
Please suggest.
$scope.boxes = [];
$scope.moving = false;
$scope.moveLeft = function() {
$scope.moving = true;
$timeout($scope.switchFirst, 1000);
};
$scope.switchFirst = function() {
$scope.boxes.push($scope.boxes.shift());
$scope.moving = false;
$scope.$apply();
};
$interval($scope.moveLeft, 2000);
Update
The following is my controller code
$scope.memoryMap = [];
$scope.loading = true;
myService.getInfo(function(metrics) {
if (metrics) {
$scope.memoryMap = metrics.memoryMap;
}
});
$scope.moving = false;
$scope.moveLeft = function() {
$scope.moving = true;
$timeout($scope.switchFirst, 1000);
};
$scope.switchFirst = function() {
$scope.memoryMap.push($scope.memoryMap.splice(0, 1)[0]);
$scope.moving = false;
$scope.$apply();
};
$interval($scope.moveLeft, 2000);

Bootstrap angular error message leave space after fading

I've found an example: Here. But after the error message fades, the content keeps the space occupied by the message.
Here's my code. In my view:
<div data-ng-show="showError" ng-class="{fade:doFade}" class="alert alert-danger"> {{authmessage}}</div>
And in my controller:
$scope.userLogin = function () {
http.post('/api/login/', $scope.formData).then(function (response) {
$rootScope.message = response.config.data.email;
$location.url('/Projects');
}).catch(function(response){
$scope.showError = false;
$scope.doFade = false;
$scope.showError = true;
$scope.authmessage = response.data;
$timeout(function(){
$scope.doFade = true;
}, 2500); });
} ;
Please set $scope.showError to false in $timeout function
$timeout(function(){
$scope.doFade = true;
$scope.showError = false;
}, 2500);

ngResourc:generate unique number

I'm trying to post new data comment and I want $resource serviceto give every comment unique id automatically.but I don't know how to do it . the data was past but in id was property empty ,it don't have id number.
Code for controller.js
.controller('ContactController', ['$scope','FeedbackFactory', function($scope,FeedbackFactory) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" ,id:""};
var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];
$scope.channels = channels;
$scope.invalidChannelSelection = false;
$scope.fback= FeedbackFactory.putFeedback().query(
function(response){
$scope.fback = response;
},
function(response) {
$scope.message = "Error: "+response.status + " " + response.statusText;
}
);
}])
.controller('FeedbackController', ['$scope', 'FeedbackFactory',function($scope,FeedbackFactory) {
$scope.sendFeedback = function() {
console.log($scope.feedback);
if ($scope.feedback.agree && ($scope.feedback.mychannel === "")) {
$scope.invalidChannelSelection = true;
console.log('incorrect');
}
else {
$scope.invalidChannelSelection = false;
$scope.fback.push($scope.feedback);
FeedbackFactory.putFeedback().save($scope.fback);
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.feedback.mychannel="";
$scope.feedbackForm.$setPristine();
console.log($scope.feedback);
}
};
}])
service.js
.service('FeedbackFactory',['$resource','baseURL',function($resource,baseURL){
this.putFeedback = function(){
return $resource(baseURL+"feedback/",{'update':{method:'POST'}});
};
} ])
;
note:the data comment will save in form of JSON data.

Return value from Angular Service

Hi I do not understand why always I get empty array from this service when is invoked by my controller
angular
.module('dimecuba.services', [])
.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contactsFound = [];
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
//options.fields = ['displayName'];
options.hasPhoneNumber = true;
$ionicPlatform.ready(function(){
$cordovaContacts.find(options).then(
function(allContacts){
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
console.log("Contacts Found:" + JSON.stringify(contactsFound));
return contactsFound;
},
function(contactError){
console.log('Error');
}
);
});
}
}; //end contacts
console.log("Contacts:"+JSON.stringify(contacts));
return contacts;
});
Use return to chain promises. A return statement needs to be included at each level of nesting.
app.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
options.hasPhoneNumber = true;
//return promise
return $ionicPlatform.ready().then(function() {
//return promise to chain
return $cordovaContacts.find(options)
}).then(function(allContacts){
var contactsFound = [];
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
//return to chain data
return contactsFound;
}).catch(function(contactError){
console.log('Error');
//throw to chain error
throw contactError;
});
}
}; //end contacts
return contacts;
});
In the controller, use the promise returned.
app.controller("myCtrl", function($scope,Contacts) {
var contactsPromise = Contacts.all();
contactsPromise.then( function(contactsFound) {
$scope.contactsFound = contactsFound;
});
});

Splitting a controller in 2 different files. Angular

I am getting a headache trying to do this, I have a very big controller which I need to split, this controller has 177 lines already so I need 2 controllers. Once I try to split it my app breaks down.
Maybe you could help by giving suggestions on how to start and what I have to evaluate first. I am new to Angular and I thought it would be easier.
'use strict';
angular.module('capilleira.clickAndGambleMobile.controllers')
.controller('LinesController', function($scope, $timeout, $state,
$stateParams, $ionicLoading, $rootScope, LinesFactory, BetSlipFactory) {
$scope.picksCount = false;
var validateSanitizeLineParams = function() {
var lineParamsOk = false;
if (validator.isAlphanumeric($stateParams.customerId) &&
validator.isNumeric($stateParams.familyGameId) &&
validator.isNumeric($stateParams.games) &&
validator.isNumeric($stateParams.top) &&
validator.isNumeric($stateParams.sports) &&
validator.isLength($stateParams.leagues.trim(), 1) &&
validator.isAscii($stateParams.leagues.trim()) &&
validator.isLength($stateParams.periods.trim(), 1) &&
validator.isAscii($stateParams.periods.trim())) {
lineParamsOk = true;
_.each($stateParams.periods.split(','), function(periodId) {
if (!validator.isAlpha(periodId)) {
lineParamsOk = false;
}
});
_.each($stateParams.leagues.split(','), function(leagueId) {
if (!validator.isNumeric(leagueId)) {
lineParamsOk = false;
}
});
}
return lineParamsOk;
};
$scope.lineItems = [];
$rootScope.spinnerTitle = 'Loading lines';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$scope.doRefresh = function() {
if (validateSanitizeLineParams()) {
LinesFactory.getLines($stateParams).then(function(linesPerLeague) {
_.each(linesPerLeague, function(linesPerParent) {
_.each(linesPerParent, function(lines) {
_.each(lines, function(line) {
_.each(line.rows, function(row) {
if (!row.noSpread) {
line.displaySpreadButton = true;
}
if (!row.noTotal) {
line.displayTotalButton = true;
}
if (!row.noMoneyLine) {
line.displayMoneyLineButton = true;
}
});
if (line.displaySpreadButton) {
line.displaySpread = true;
} else if (line.displayTotalButton) {
line.displayTotal = true;
} else if (line.displayMoneyLineButton) {
line.displayMoneyLine = true;
}
});
});
});
$scope.lineItems = linesPerLeague;
if (!$scope.lineItems[0].length) {
$state.go('app.noLines');
}
$ionicLoading.hide();
$scope.addLineSelections();
}, function(err) {
console.log(err);
$rootScope.spinnerTitle = 'Wrong Params';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$timeout(function() {
$ionicLoading.hide();
$state.go('app.login');
}, 1500);
});
}else {
$rootScope.spinnerTitle = 'Wrong Params';
$ionicLoading.show({
templateUrl: 'templates/loaders.html',
scope: $rootScope
});
$timeout(function() {
$ionicLoading.hide();
$state.go('app.login');
}, 1500);
}
$scope.$broadcast('scroll.refreshComplete');
};
$scope.doRefresh();
$scope.showLine = function(lineType, line) {
switch (lineType) {
case 'spread':
line.displayTotal = false;
line.displayMoneyLine = false;
line.displaySpread = false;
$timeout(function() {
line.displaySpread = true;
}, 50);
break;
case 'total':
line.displaySpread = false;
line.displayMoneyLine = false;
line.displayTotal = false;
$timeout(function() {
line.displayTotal = true;
}, 50);
break;
case 'moneyline':
line.displaySpread = false;
line.displayTotal = false;
line.displayMoneyLine = false;
$timeout(function() {
line.displayMoneyLine = true;
}, 50);
break;
}
};
$scope.addLineToBetSlip = function(line, row, type) {
var spreadSelected = (row.spreadSelected && type === 'spread'),
totalSelected = (row.totalSelected && type === 'total'),
moneyLineSelected = (row.moneyLineSelected && type === 'moneyline');
if (spreadSelected || totalSelected || moneyLineSelected) {
BetSlipFactory.remove(line, row, type);
}else {
BetSlipFactory.add(line, row, type);
}
$scope.picksCount = !$scope.picksCount;
};
$scope.addLineSelections = function() {
BetSlipFactory.getBetSlip().then(function(betSlip) {
var flattenLines = _.flatten($scope.lineItems),
lineFound, row;
_.each(betSlip, function(slip) {
lineFound = _.find(flattenLines, function(line) {
return line.gameId === slip.gameId &&
line.part === slip.part &&
line.lineTypeName === slip.lineTypeName;
});
if (lineFound) {
row = _.find(lineFound.rows, function(row) {
return row.nss === slip.nss;
});
if (row) {
switch (slip.type) {
case 'spread':
row.spreadSelected = true;
break;
case 'total':
row.totalSelected = true;
break;
case 'moneyline':
row.moneyLineSelected = true;
break;
}
}
}
});
});
};
});
This works as expected.
var app = angular.module('plunker', []);
var FatCtrl1 = function($scope){
$scope.stuff1 = this.hello;
};
var FatCtrl2 = function($scope){
$scope.stuff2 = "World";
};
app.controller('FatCtrl', function($scope) {
this.hello = "Hello";
FatCtrl1.apply(this, arguments);
FatCtrl2.apply(this, arguments);
});
Beware of closures. Variables within FatCtrl are not available in the partitions. 'this' is used to share data.

Resources