Hey so I have a form which has three fields name,email and phone.
<div ng-show="Nerd.adding">
<form class="col-sm-6" name="Nerd.nerdAddFrm" novalidate >
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Name" ng-model="Nerd.nerd.name" required >
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Email" ng-model="Nerd.nerd.email" required >
</div>
<div class="form-group">
<label for="inputPhone">Phone</label>
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" ng-model="Nerd.nerd.phone" required >
</div>
<button ng-click="Nerd.saveNerd(Nerd.nerd)" type="submit" class="btn btn-primary">Submit</button>
<button ng-click="Nerd.load()" type="button" class="btn btn-default">Cancel</button>
</form>
</div>
As you can see the cancel button calls a Nerd.load() function in the controller. The controller basically resets the view and resets all the binded data to the model.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
}
);
};
You can see that I am setting Nerd.nerd equal to an empty array. This should empty out the form fields data. It works fine for Name and Phone. But when I go back to the page it still shows what was last typed. There is no page reload as I am showing and hiding divs based on controller variables. EG <div ng-show="Nerd.adding">. Can anyone help me out with this?
I am on angularjs version 1.3.14. Any help on this would be great.
Thanks.
You need to attach these variables to your $scope like so:
$scope.Nerd.load = function () {
$scope.Nerd.editing = false;
$scope.Nerd.adding = false;
$scope.Nerd.nerd = [];
nerdResource.query(
function (data) {
$scope.Nerd.nerds = data;
}
);
};
Also, I think you should set $scope.Nerd to an empty object like:
$scope.Nerd = {};
instead of setting it to an empty array. You need to use $scope when interacting with the view. This code doesn't look the angular the way it is currently written.
If you can try according some way.
Nerd.load = function () {
Nerd.editing = false;
Nerd.adding = false;
Nerd.nerd = [];
nerdResource.query(
function (data) {
Nerd.nerds = data;
Nerd.nerd = []; // Put here and array make Empty
}
);
};
Related
I seem to be overlooking something simple here but it has me stumped.
Why does nothing happen when i hit the submit button?
<section ng-controller="SavingsController as savingsCTRL">
<form name="createSavingForm" class="form-horizontal" novalidate>
<fieldset>
<!-- Title Box Start-->
<div class="form-group new-deal-form" show-errors>
<label for="title">Title</label>
<input name="title" type="text" ng-model="savingsCTRL.title" id="title" class="form-control" placeholder="Title" required>
<div class="sub-label">Enter the Title of the Deal.</div>
<div ng-messages="savingForm.savingsCTRL.title.$error" role="alert">
<p class="help-block error-text" ng-message="required">Saving title is required.</p>
</div>
</div>
<!-- Title Box End-->
<!--Submit Button Start-->
<div class="form-group buttons-cancel-submit">
<button class="btn btn-default " ng-click="savingsCTRL.cancel()">Cancel</button>
<input type="submit" class="btn btn-success " ng-click="savingsCTRL.create(); submitForm(createSavingForm.$valid)" >
</div>
</fieldset>
</form>
</div>
</div>
</section>
for simplicity i took most of the forms out but what else is wrong?
Savings Controller Function
// Create new Saving
$scope.create = function () {
$scope.error = null;
alert("create");
// Create new Saving object
var saving = new Savings({
title: this.title,
details: this.details,
retailer: this.retailer,
price: this.price,
link: this.link,
image: $scope.user.imageURL,
urlimage: this.urlimage,
tags: this.tags
//startdate: this.startdate,
//enddate: this.enddate
});
// Redirect after save
saving.$save(function (response) {
$location.path('savings/' + response._id);
// Clear form fields
$scope.title = '';
$scope.details = '';
$scope.retailer = '';
$scope.price = '';
$scope.link = '';
$scope.image = '';
$scope.urlimage = '';
$scope.tags = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
Main issue is, you are mixing controller as syntax with $scope.
According to documentation, we should use this instead of $scope.
... binds methods and properties directly onto the controller using this: ng-controller = "SettingsController1 as settings"
Than, submitForm is not a predefined method, it should be defined in controller first
this.submitForm = function(isValid){
console.log('Submitting form: ' + isValid)
}
In addition to that, bind that to form with ng-submit= "savingsCTRL.submitForm(createSavingForm.$valid)"
See Plunker, with working code. (I took ng-click="savingsCTRL.create()", since we don't have all parts of your application)
Bind the form submit event to ng-submit.
Example: ng-submit="submitForm(createSavingForm.$valid)"
I have a select dropdown for returnreasons that is populated from DB. If user is in specific role he can add new reasons. The problem is that my model in dropdown is not updating automatically after adding? The adding goes to DB though, but in the view dropdown is not populated again even if the model has changed.
<select class="form-control" ng-model="selectedReason">
<option ng-selected="{{reason.returnreasonId === selectedReason}}"
ng-repeat="reason in returnreasons"
value="{{reason.returnreasonId}}">
{{reason.returnText}}
</option>
</select>
<div class="form-group form-group-lg" ng-show="addReasonToggle">
<label class="col-md-2 control-label">New reason:</label>
<div class="col-md-8">
<input type="text" class="form-control" ng-model="returnReason.returnText" placeholder="New reason for return">
</div>
<div class="col-md-2">
<button class="btn btn-small btn-primary" ng-click="addNewReturnReason(returnReason)">Lisää</button>
</div>
</div>
In controller
$scope.addNewReturnReason = function(returnReason){
var savedReturnReason = [];
if (returnReason === undefined || returnReason === null) {
console.log("returnReason null");
} else {
// This is default value
returnReason.languageLanguageId = $scope.languages[0];
savedReturnReason = returnReasonSvc.save({}, returnReason);
savedReturnReason.$promise.then(function (result) {
$scope.returnReason = result;
$scope.returnreasons = returnReasonSvc.query();
$scope.addReasonToggle = false;
$scope.selectedReason=savedReturnReason;
});
};
}
Could be a problem of watch cycle is not running you can try this in your then function..
$scope.$apply();
to run manually .hope so it will work .
Can't access form variable from my controller, when i try to access it by $scope.locationForm i've got 'undefined', but when i call console.log($scope) i can see in console there have loactionForm.
My HTML code
<div ng-controller="LocationsController as ctrl">
<form class="form-inline" name="locationForm">
<div class="form-group">
<!-- <div class="input-group"> -->
<label for="location-name">Название населенного пункта</label>
<input required
name="name"
ng-model="ctrl.location.name" type="text" class="form-control" id="location-name" placeholder="Название населенного пункта">
<label for="location-name">Район</label>
<select required
name="region_id"
ng-model="ctrl.location.region_id"
ng-options="region.id as region.name for region in ctrl.regions" class="form-control" placeholder="Название района"></select>
<input ng-click="ctrl.save()"
ng-disabled="locationForm.$invalid" type="submit" class="btn btn-default" value="Cохранить">
<a class="btn btn-default" ng-click="ctrl.reset()" ng-show="locationForm.$dirty">Сброс</a>
<!-- </div> -->
</div>
</form>
My Controller code:
function LocationsController($scope, Location, Region, $q) {
var lc = this,
l_index;
lc.form ={};
lc.regions = lc.locations = [];
lc.regions = Region.query();
lc.regions.$promise.then(function(data) {
lc.locations = Location.query();
});
lc.getRegion = function (id) {
return lc.regions.filter(function(obj) {
return obj.id == id;
})[0].name;
};
console.log($scope);
// console.log($scope.locationForm);
lc.reset = function () {
lc.location = new Location;
}
lc.reset();
};
The problem is when the LocationsController is initialized the form element is not yet compiled. So one possible hack is to use a timeout like
function LocationsController($scope, Location, Region, $q, $timeout) {
//then later
$timeout(function(){lc.reset();})
}
I have a input field like this :
<div class="form-group form-group-sm">
<label for="antispam" class="col-sm-2 control-label">1+1+5 = ?
<span class="myForm_error" ng-show="myFormZR.antispam.$error.required">(required field)</span>
<span ng-show="myFormZR.antispam.$dirty && IsMatch">BAD ANSWER</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="antispam" placeholder="" required="required" ng-model="myForm.antispam" />
</div>
</div>
in ctrl :
/* antispam */
var antispamAnswer = "7"
if ($scope.myForm.antispam != antispamAnswer) {
$scope.IsMatch = true;
} else {
$scope.IsMatch = false;
}
It's not working, the mention "BAD ANSWER" is always show
Your code runs only once, when Controller is instantiated. You need put that code inside of $watch function for that ng-model:
$scope.$watch('myForm.antispam', function() {
// that code
})
Also do lots of console.log() to debug your code, so you know what and when is happening in your application.
I'm trying to code a controller so some inputs get disabled after changes in another one.
This is the controllre:
app.controller('SignUpController',function ($scope, $http) {
this.unavaliable = true
this.userUnavaliable = function() {
console.log(this.unavaliable)
return this.unavaliable
}
this.userExists = function(mail) {
if (mail) {
var who = $http.get("/existingUsers/"+mail)
who.success(function(data,status, headers, config) {
if (data.mail) {
this.unavaliable = true
console.log(data.mail + " ya existe en la DB")
}
else{
this.unavaliable = false
}
});
who.error(function(data, status, headers, config) {
alert("AJAX failed!");
})
}
}
})
As my markup below shows, one input should obtain a certain class, and another one should get disabled when unavaliable is set to true. But even I can get to the console.log(), the variable seems to never get true.
This is my markup:
<form class="form-inline" role="form">
<div class="form-group">
<input type="email" class="form-control input-lg" ng-model="signup.mail" placeholder="e-mail" ng-change="signup.userExists(signup.mail)" ng-class="{'has-error':signup.userUnavaliable()}">
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" placeholder="Contraseña" ng-nodel="signup.password">
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="signup.role" value="admin"> Administrador
</label>
</div>
<button type="submit" class="btn btn-primary" ng-disabled="signup.unavaliable" >Registrar</button>
</form>
I tried with $scope instead of this but never got it to work that way
Try this:
app.controller('SignUpController',function ($scope, $http) {
var that = this;
that.unavaliable = true;
that.userUnavaliable = function() {
console.log(that.unavaliable)
return that.unavaliable
}
that.userExists = function(mail) {...
Your issue seems to be related to JS Context; in the example above it is preserved in that variable. That is how it is done in JOhn's Papa approach