I am using basic angular.js concept to show and hide a div. For some reasons I am unable to make it work.
While Uploading a file I am showing a div 'myFormSpinner' on the basis of registerStart value. I am creating a phone gap app.
Could someone please help me in finding the issue. Apart from showing/hiding div everything works fine. Below is the code snippet:
<div class="row" ng-controller="RegisterCtrl">
<div id="myFormSpinner" ng-show="registerStart">
<img src="img/ajax-loader.gif">
</div>
<div class="col-md-8">
<form class="ng-pristine ng-invalid ng-invalid-required" style="margin-top:5%;">
<div class="col-md-6">
<input class="form-control " type="text" ng-model="registerData.Email" id="Email" name="Email" required placeholder="Email">
</div>
<div class="col-md-offset-1 col-md-10 ">
<input type="submit" ng-click="register()" value="Register" class="btn btn-default btn-primary">
</div>
</form>
</div>
event.controller('RegisterCtrl', ['$scope', '$state', '$q', '$http', 'eventService', 'authService', '$stateParams', '$rootScope', 'tokenService', 'imageService', 'spinnerService', 'appBackgroundService',
function ($scope, $state, $q, $http, eventService, authService, $stateParams, $rootScope, tokenService, imageService, spinnerService, appBackgroundService) {
var userNumber = 0;
$scope.mediaUploadStart = false;
$scope.eventId = $state.params.id;
$scope.register = function () {
$scope.registerStart = true;
console.log('scope.Pic=' + $scope.pic);
if ($scope.registerData.Email) {
spinnerService.show('myFormSpinner');
$scope.mediaUploadStart = true;
var paramOptions = {
eventId: $state.params.id,
email: $scope.registerData.Email,
fb: {},
number: userNumber,
provider: "Form"
};
uploadPicAndData(paramOptions).then(function (result) {
var data = JSON.parse(result);
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
},
function (error) {
spinnerService.hide('myFormSpinner');
$scope.registerStart = false;
appBackgroundService.disableBackgroundMode();
});
$scope.mediaUploadStart = false;
spinnerService.hide('myFormSpinner');
}
};
}])
You are setting the $scope element in an async mode.
the digest cycle is not able to determine that a change has been made to the scope element in an async mode.
You should use $apply to activate the digest cycle.
$scope.$apply(function () { $scope.registerStart = false; });
Read more about $apply here: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
Related
Hi i am beginner for angularJS and i am showing angular-ui modal form when click on button and have to add new user but i am really confusing how to handle and how to do this scenario and i tried below code but its not working can some one help me better way to do this
My requirement i want to open modal form for adding new user and when i click save button i need to add that new user in my array
main.js
// create the module, pass in modules it depends on
var app = angular.module('myApp', ['ui.bootstrap']);
// $modal service is now available via the ui.bootstrap module we passed in to our module
app.controller('myController', ['$scope', '$uibModal', '$log',
function ($scope, $uibModal, $log) {
$scope.newUser = {};
$scope.info = "";
$scope.users = [
{ username: "rimon", fullName: "Md. Mamunur Rashid Rimon", email: "rimonmath#gmail.com" },
{ username: "shamim", fullName: "Md. Tamim Hossain", email: "shamim#gmail.com" },
{ username: "tamim", fullName: "Tamim Iqbal", email: "tamim#gmail.com" }
];
$scope.addUser = function () {
var modalInstance = $uibModal.open({
templateUrl: 'add_user.html',
controller: 'ModalInstanceCtrl',
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
$scope.saveUser = function () {
console.log("Saving...");
$scope.users.push($scope.newUser);
$scope.info = "New User Added Successfully!";
$scope.newUser = {};
};
$scope.selectUser = function (user) {
$scope.clickedUser = user;
};
$scope.deleteUser = function () {
console.log($scope.users.indexOf($scope.clickedUser));
$scope.users.splice($scope.users.indexOf($scope.clickedUser), 1);
$scope.info = "User Deleted Successfully!";
};
$scope.clearInfo = function () {
$scope.info = "";
};
}]);
angular.module('myApp').controller('ModalInstanceCtrl', function ($scope,$uibModalInstance) {
$scope.saveUser = function () {
alert("You clicked the ok button.");
$uibModalInstance.close();
};
$scope.close = function () {
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
Form.html
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">New User Registration</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Username" ng-model="newUser.username">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Email" ng-model="newUser.email">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Full Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputEmail3" placeholder="Full Name" ng-model="newUser.fullName">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="saveUser();">Save</button>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" ng-click="close()">Close</button>
</div>
</div>
From what I see, your problem lies in your declaration of FormController.js please try to change this code :
app.controller('ModalInstanceCtrl', ['$scope','$modalInstance',function ($scope, $modalInstance) {
$scope.close = function () {
$modalInstance.dismiss('cancel');
};
$scope.saveUser = function(){
//SUBMIT FORM HERE
}
}]);
for this one :
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($uibModalInstance, data)
{
var pc = this;
pc.data = data;
pc.ok = function () {
//{...}
alert("You clicked the ok button.");
$uibModalInstance.close();
};
pc.cancel = function () {
//{...}
alert("You clicked the cancel button.");
$uibModalInstance.dismiss('cancel');
};
});
From your code I noticed that:
Your declaration of the modal controller misses the name of the main module app which sometimes is required.
you are using '$modalInstance' instead of $uibModalInstance
For further reference go here. Please try these changes and let me know if it works!
I tried to create a small service for adding and getting. I have successfully added details when I click register(form details are added)in one controller. Now I want that form details in another controller, but I'm not getting it. I'm able to get that details in that get function and able to print in console but I cannot pass them to html
Here is my HTML:
<div id="inputArea" style="border: 1px solid blue;width: 800px;height: 45px;margin: auto;" ng-controller="MyFormCtrl">
<form name="myForm" ng-submit="register()">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter first name" ng-model="user.fname">
<input class="inputfield" type="text" style="margin-left: 13px;" placeholder="enter last name" ng-model="user.lname">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter designation" ng-model="user.designation">
<input class="inputfield" type="text" style="margin-left: 10px;" placeholder="enter company" ng-model="user.company">
<input type="submit" style="float:right;" value="Register"> </form>
</div>
<div id="box" style="position: relative;top:200px;margin: auto;border:1px solid red;width:180px;height:90px;" ng-controller="DetailsConroller">
<input type="button" ng-click="getDetails()" value="get">
<!-- <input type="submit" style="" value="get">-->
<ul>
<li ng-repeat="x in employees"> {{ x.fname }} </li>
</ul>
</div>
my js:
var app = angular.module('myApp', []);
--->service for adding and get
app.service('employeeService', ['$rootScope', function ($rootScope) {
var employeeList = [];
return {
employeeList: []
, // var employeeList = [],
add: function (item) {
employeeList.push(item);
console.log('employeeList', employeeList);
}
, get: function () {
// console.log('in to get employeeList',employeeList);
return employeeList
}
};
}])
---->> COntroller to Add:
app.controller('MyFormCtrl', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.user = {
fname: ''
, lname: ''
, designation: ''
, company: ''
};
$scope.register = function () {
console.log('User clicked register', this.user);
employeeService.add(this.user);
//employeeService.updateUserData().set($rootScope.user);
};
}]);
--->>second controller to get:
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
var employees = [];
$scope.getDetails = function () {
// console.log('User clicked register', this.user);
employees = employeeService.get();
console.log('User in to get', employees[0].fname);
return employees;
};
}]);
what am I doing wrong here?
You need to have a $scope variable,
Change your Controller like this,
app.controller('DetailsConroller', ['$scope', 'employeeService', function ($scope, employeeService) {
$scope.employees = [];
// console.log('User clicked register', this.user);
$scope.employees = employeeService.get();
console.log('User in to get', employees[0].fname);
}]);
I'm creating a single page app in which a user searches for a term, the result gets saved in a variable, and a new page is routed that displays the result. I have this functionality working, however I want the variable to be cleared when the user returns to the previous page and most importantly when the user logs out. What's the proper way to do this? I want the factory to save things for certain pages that I want, and clear them for certain pages I don't want like "home" or "logout".
Factory:
angular.module('firstApp')
.factory('fact', function () {
var service = {};
var _information = 'Default Info';
service.setInformation = function(info){
_information = info;
}
service.getInformation = function(){
return _information;
}
return service;
});
Controller:
angular.module('firstApp')
.controller('InformationCtrl', function($scope, $http, $location, fact) {
$scope.message = 'Hello';
$scope.result = fact.getInformation();
$scope.sub = function(form) {
console.log($scope.name);
$scope.submitted = true;
$http.get('/wiki', {
params: {
name: $scope.name,
}
}).success(function(result) {
console.log("success!");
$scope.result = result;
fact.setInformation(result);
$location.path('/informationdisplay');
});;
}
});
Routes
angular.module('firstApp')
.config(function ($routeProvider) {
$routeProvider
.when('/information', {
templateUrl: 'app/information/input.html',
controller: 'InformationCtrl',
authenticate : true
})
.when('/informationdisplay', {
templateUrl: 'app/information/results.html',
controller: 'InformationCtrl',
authenticate : true
});
});
input.html
<div class="row">
<div class="col-md-6 col-md-offset-3 text-center">
<p>{{result}}</p>
<form class="form" name="form" ng-submit="sub(form)" novalidate>
<input type="text" name="name" placeholder="Name" class="form-control" ng-model="name">
</br>
<button class="btn btn-success" type="submit" class="btn btn-info">Check</button>
</div>
</div>
results.html
<div ng-include="'components/navbar/navbar.html'"></div>
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<h2>Information Results</h2>
<p>{{result}}</p>
</div>
</div>
</div>
If you want it to wipe the value when they change routes (which logout should change routes also, I assume), you can watch the $routeChangeStart event and have it wipe the value whenever it occurs. You put that function in the module.run block:
app.run(function ($rootScope, fact) {
$rootScope.$on("$routeChangeStart",function(event, next, current){
fact.setInformation(null);
});
});
I'm trying to unit test a connection forms controller with karma and jasmine, but on thing I can't get to grips with.
The controller:
.controller('connectionController', ['$scope', '$rootScope', '$state', '$stateParams', '$http', '$localStorage',
function($scope, $rootScope, $state, $stateParams, $http, $localStorage){
$scope.userCredentials = {};
$scope.connectionError = false;
$scope.connectUser=function(){
if ($scope.connectionForm.$valid) {
//Do the login stuff here
//IF good --> state.go...
}
else {
console.log('Invalide.');
$scope.connectionError = true;
}
}
}])
Then in my HTML (simplified to a maximum):
<form name="connectionForm" novalidate>
<div class="form-group input-group" show-errors='{ showSuccess: true }'>
<span for="login" class="input-group-addon"></span>
<input type="text" ng-model="userCredentials.login" required>
</div>
<div class="form-group input-group" show-errors='{ showSuccess: true }'>
<span for="password" class="input-group-addon"></span>
<input type="password" ng-model="userCredentials.password" required>
</div>
<button class="btn btn-primary" ng-click="connectUser()">Connect</button>
</form>
And finally the test (specific 'it' that doesn't pass):
it('should connect user', function(){
scope.userCredentials.login = 'aUser';
scope.userCredentials.password = 'aPassword';
$httpBackend.when('POST', 'http://localhost:4711/api/token').
respond({ token: 'xxx', user: aUser });
scope.connectUser();
$httpBackend.flush();
});
So the the problem I get is that this:
TypeError: Cannot read property '$valid' of undefined
at Scope.$scope.connectUser (connection.js)
at null.<anonymous> (connection.js)
Si I think the basic problem comes from the fact that the controller doesn't have the access to stuff defined only on the html (like connectionForm...) and cannot get their properties.
Another thing to notice is that I do a state.go(..) when the connection was successful, could it be this ?
What can I do ? Or more, what am I doing wrong ?
I'm setting up registration/login functionality using angular, Firebase, and firebaseSimpleLogin. After reading over a few tutorials and another Stack Overflow thread, I've got the registration working with one small but important caveat: the promise on the SimpleLogin $createUser function isn't resolving until I click on a link or button on my html page. Here's my code:
Register.html
<div class="form-group" >
<label class="control-label" for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" ng-model="cred.email"/>
<label class="control-label" for="password">Password</label>
<div class="form-group">
<input class="form-control" type="password" name="password" id="password" ng-model="cred.password"/>
</div>
<div class="form-group">
<input type="submit" value="Register" class="btn btn-primary" ng-click="register()"/>
</div>
</div>
Main.Js
angular.module('myApp')
.controller('AuthCtrl',
['$scope',
'$location',
'$firebase',
'$firebaseSimpleLogin',
'loginService',
function AuthCtrl($scope, $location, $firebase, $firebaseSimpleLogin,
loginService) {
$scope.register = function(){
var user = {
email: $scope.cred.email,
password: $scope.cred.password
};
loginService.register(user);
};
});
loginService.js (note FBURL is defined elsewhere)
angular.module('myApp')
.factory('loginService', function($firebaseSimpleLogin, $rootScope, $location,
$timeout) {
var ref = new Firebase(FBURL);
var auth = $firebaseSimpleLogin(ref);
return {
register: function (user) {
return auth.$createUser(user.email, user.password)
.then(function(registeredUser) {
console.log(registeredUser);
}
)}
});
In the above loginService.js, I'm not seeing the console.log until I click a button or element; however, the user is created in the Firebase Simple Login DB when I look online. As soon as I click a button or element, the console.log shows. My guess as to the issue is that the promise from auth.$createUser() isn't getting resolved, but I cannot find out why that would be.