angularjs clean input field after submission - javascript

trying to clear input filed after button is clicked and post saved with angular but it does not work. here is a simple code
<!--html-->
<input type="text" ng-model="addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.addField = '';
function addPost(item) {
/*code for adding*/
$scope.addField = "";
}

Use a object instead of string, Try this
<!--html-->
<input type="text" ng-model="form.addField"/>
<button type="button" ng-click="addPost(item)">add</button>
/*script*/
$scope.form = {};
$scope.addPost = function(item) {
/*code for adding*/
$scope.form = {};
}

Related

Mapping not working in knockout with the button click

Mapping not working in knockout with the button click,
I have used mapping in knockout, while changing input text value when clicking button not changed properly.
Need to change value for name input text after click load user data button
Here my code,
<div class='sample'>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>
<p>Save: <input type="button" value="Save User Data" data-bind="click: saveUserData" /></p>
</div>
<script>
$(document).ready(function () {
var viewModel = {};
viewModel.firstName = 'Knockout JS';
viewModel.loadUserData = function () {
$.getJSON("/data.json", function (data) {
// update the data in existing ViewModel.
viewModel.firstName = data.name;
ko.mapping.fromJS(data, viewModel);
});
};
viewModel.saveUserData = function () {
// Convert the viewModel into JSON.
var data_to_send = { userData: ko.toJSON(viewModel) };
// Send that JOSN data to server.
$.post("WebService.asmx/updateData", data_to_send, function (data) {
alert("Your data has been posted to the server!");
});
};
ko.applyBindings(viewModel);
});
</script>
Did i anything wrong?
In order to make it update the UI, you need to make the firstName observable.
Then when you want to modify an observable value, you need to treat that as a function and pass the new value as an argument like this firstName('newValue')
See the link here to get more information and a sample below:
var masterVM = (function () {
var self = this;
self.firstName = ko.observable("Knockout JS");
self.loadUserData = function() {
var currentName = self.firstName();
self.firstName(currentName + "Updated");
}
})();
ko.applyBindings(masterVM);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Load: <input type="button" value="Load User Data" data-bind="click: loadUserData" /></p>
<p>Name: <input data-bind='value: firstName' /></p>

How to bind a value from one ng-model to an other by matching a specific string

I got a requirement to bind a value to a particular model when the value in the other model contains a string starting with "https".
For example, I have two text fields both fields having different model
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
Suppose I type a value on the first text field "https", the first input model modelText1 have to bind to the second input model modelText2 and later on i have to maintain it as like two-way binding. i.e. the second field will automatically get the value dynamically when it contains "https" at starting of a string.
Try it like in this Demo fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.$watch('modelText1', function (newValue) {
if (newValue.toLowerCase().match(regEx)) {
$scope.modelText2 = newValue;
} else {
$scope.modelText2 = '';
}
});
});
An other approach is (that avoid using of $watch) is to use AngularJS ng-change like in this
example fiddle.
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" ng-change="change()">
<input type="text" ng-model="modelText2">
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
var regEx = new RegExp(/^https/);
$scope.change = function () {
if ($scope.modelText1.toLowerCase().match(regEx)) {
$scope.modelText2 = $scope.modelText1;
} else {
$scope.modelText2 = '';
}
};
});
You can use the ng-change directive like this:
<input type="text" ng-model="modelText1" ng-change="onChange()">
<input type="text" ng-model="modelText2">
and your controller:
$scope.onChange = function() {
if ($scope.modelText1 === 'https') {
$scope.modelText2 = $scope.modelText1;
else
$scope.modelText2 = '';
};
use ng-change to check the text is equal to 'https'
angular.module('app',[])
.controller('ctrl',function($scope){
$scope.changeItem = function(item){
$scope.modelText2 = "";
if(item.toLowerCase() === "https"){
$scope.modelText2 = item
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="modelText1" ng-change="changeItem(modelText1)">
<input type="text" ng-model="modelText2">
</div>
EDiTED
to make sure it does't fail under 'HTTPS' use toLoweCase function to make all lower case
HTML :
<input type="text" ng-model="modelText1" ng-change="updateModal(modelText1)">
JS :
var modelText1 = $scope.modelText1.toLowerCase();
$scope.updateModal = function(){
$scope.modelText2 = '';
if(modelText1.indexOf('https')!=-1){
$scope.modelText2 = modelText1;
}
}
you could also possibly do this as a directive if you want to have a more reusable solution over multiple views http://jsfiddle.net/j5ga8vhk/7/
It also keeps the controller more clean, i always try to use the controller only for controlling complex business logic and business data
View
<div ng-controller="MyCtrl">
<input type="text" ng-model="modelText1" >
<input type="text" ng-model="modelText2" model-listener="modelText1" model-listener-value="https" >
</div>
Angular JS
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
$scope.modelText1 = '';
$scope.modelText2 = '';
});
myApp.directive('modelListener', [function() {
return {
restrict: 'A',
controller: ['$scope', function($scope) {
}],
link: function($scope, iElement, iAttrs, ctrl) {
$scope.$watch(iAttrs.modelListener, function() {
if($scope[iAttrs.modelListener] === iAttrs.modelListenerValue ) {
$scope[iAttrs.ngModel] = $scope[iAttrs.modelListener];
} else {
$scope[iAttrs.ngModel] = "";
}
}, true);
}
};
}]);

form does not submit when using ng-click

I have a simple form which need to submit when click button and hide stuff with ng-click, it does submit the form when I don't add the ng-click for the hide stuff purpose, when I add the ng-click the form don't submit:
the form head :
<form class="form" name="form" ng-submit="edit(form)" novalidate ng-show="editorEnabledView">
the button :
<button analytics-on analytics-event="Bouton Terminer" analytics-category="Profil" ng-click="disableEdditing()" class="btn btn-lg btn-primary" type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}</button>
CTRL
$scope.editorEnabledView = false;
$scope.showEdditing = function () {
$scope.editorEnabledView = true;
console.log("YES TRUE");
}
$scope.disableEdditing = function () {
$scope.editorEnabledView = false;
}
my edit function :
$scope.edit = function (form) {
if (!form.$valid) return;
$scope.errors = {};
if (!$scope.address.input) $scope.errors.address = 'Votre adresse de travail est obligatoire.';
var data = {
gender: $scope.user.gender,
name: {
first: $scope.user.name.first,
last: $scope.user.name.last
},
phone: $scope.user.phone,
job: {
name: $scope.user.job.name,
status: $scope.user.job.status
},
about: $scope.user.about,
interests: $scope.user.interests
};
getAddress(function (response) {
data.address = {
full: response.formatted_address,
city: getCity(response.address_components),
latitude: response.geometry.location.lat(),
longitude: response.geometry.location.lng(),
timestamp: new Date()
};
User.update(data, function (user) {
submit = true;
Auth.update(user);
if ($scope.step == 1) return $scope.step++;
$location.path($scope.step == 2 ? '/' : '/users/view/' + user._id);
}, function (err) {
Auth.update(originalUser);
$scope.user = originalUser;
angular.forEach(err.data.errors, function (error, field) {
$scope.errors[field] = error.message;
});
});
});
//$scope.editorEnabledView = false;
};
I discovered that when go to another page and come back to the user profile I see that the form get submitted !! but I want to see it after the submit
I had to change my answer cause now its clear that all you want to do is to hide your form after submit. This can be done with the use of form.$submitted and ng-hide
<div ng-controller="MyCtrl">
<form class="form" name="form" ng-submit="edit(form)" ng-hide="form.$submitted" ng-show="!form.$submitted" novalidate >
</div>
<button analytics-on analytics-event="Bouton Terminer" analytics-category="Profil" class="btn btn-lg btn-primary" type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}</button>
I did a snippet and everything seems to be working... I think you are doing something wrong. Maybe you are missing the ng-submit in the form tag. See my snippet and change your code.
var $scope = {};
var myApp = angular.module('myApp', []);
myApp.controller('ngSubmitCtrl', ['$scope', function($scope){
$scope.editorEnabledView = true;
$scope.showEdditing = function () {
$scope.editorEnabledView = true;
alert("showEdditing");
}
$scope.disableEdditing = function () {
$scope.editorEnabledView = false;
alert("disableEdditing");
}
$scope.edit = function (form) {
alert("submitForm");
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="ngSubmitCtrl">
<form class="form" name="form" ng-submit="edit(form)" novalidate ng-show="editorEnabledView">
<button
analytics-on analytics-event="Bouton Terminer"
analytics-category="Profil"
ng-click="disableEdditing()"
class="btn btn-lg btn-primary"
type="submit">{{ step == 2 ? 'Terminer' : 'Enregistrer' }}
</button>
</form>
</div>
Why do you send form inside edit call?
<form class="form" name="form" ng-submit="edit()">
<input type="text" ng-model="formData.name">
</form>
in your controller
$scope.edit = function() {
console.log($scope.formData)
}
Or if you want to call edit function with parameter means
<form class="form" name="form" ng-submit="edit(form)">
<input type="text" ng-model="form.name">
</form>
in your controller
$scope.edit = function(data) {
console.log(data)
}
This should work. But we don't get your problem. If you show full code, we will help.

Show only clicked element values from multiple ng-click events angularjs

i have 10 more ng-click events, but i want to show only clicked element value where i have to change, but i updated in code there was so many true or false duplicates i have to write, pls help me that have to show only clicked ng-show values without using 'true or false' booleen functions in each click event.
var app = angular.module('myapp', ['ngSanitize']);
app.controller('AddCtrl', function ($scope, $compile) {
$scope.field = {single: 'untitled',single2:'default',single3:'enter'};
$scope.addName1 = function (index) {
var name1html = '<fieldset id="name1" ng-click="selectName1($index)"><label ng-bind-html="field.single"></label><input type="text" placeholder="Enter name"><button ng-click="removeName1($index)">-</button></fieldset>';
var name1 = $compile(name1html)($scope);
angular.element(document.getElementById('drop')).append(name1);
};
$scope.removeName1 = function (index) {
var myEl = angular.element(document.querySelector('#name1'));
myEl.remove();
};
$scope.selectName1 = function (index) {
$scope.showName1 = true;
$scope.showName2 = false;
$scope.showName3 = false;
};
$scope.addName2 = function (index) {
var name2html = '<fieldset id="name2" ng-click="selectName2($index)"><label ng-bind-html="field.single2"></label><input type="text" placeholder="Enter name"><button ng-click="removeName2($index)">-</button></fieldset>';
var name2 = $compile(name2html)($scope);
angular.element(document.getElementById('drop')).append(name2);
};
$scope.removeName2 = function (index) {
var myEl = angular.element(document.querySelector('#name2'));
myEl.remove();
};
$scope.selectName2 = function (index) {
$scope.showName2 = true;
$scope.showName1 = false;
$scope.showName3 = false;
};
$scope.addName3 = function (index) {
var name3html = '<fieldset id="name3" ng-click="selectName3($index)"><label ng-bind-html="field.single3"></label><input type="text" placeholder="Enter name"><button ng-click="removeName3($index)">-</button></fieldset>';
var name3 = $compile(name3html)($scope);
angular.element(document.getElementById('drop')).append(name3);
};
$scope.removeName3 = function (index) {
var myEl = angular.element(document.querySelector('#name3'));
myEl.remove();
};
$scope.selectName3 = function (index) {
$scope.showName3 = true;
$scope.showName1 = false;
$scope.showName2 = false;
};
});
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular-sanitize.min.js"></script>
</head>
<body ng-controller="AddCtrl">
<div id="drop"></div>
<button ng-click="addName1($index)">Name1</button>
<button ng-click="addName2($index)">Name2</button>
<button ng-click="addName3($index)">Name3</button>
<form ng-show="showName1">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single">
</div>
</form>
<form ng-show="showName2">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single2">
</div>
</form>
<form ng-show="showName3">
<div class="form-group">
<label>Field Label(?)</label>
<br/>
<input ng-model="field.single3">
</div>
</form>
</body>
</html>
here is plunkr http://plnkr.co/edit/oFytWlQMIaCaeakHNk71?p=preview
You will need "ng-repeat" in the HTML. Set an Array on $scope and let the template determine what HTML elements to add. Typically, $index is only set by ng-repeat.
Read more here: https://docs.angularjs.org/api/ng/directive/ngRepeat

Hide a Current Button on ng-click

I have a button for updating data in ng-form. This button only appear when some form input is changed. I done this with $dirty.
When the Update is clicked, I update the data. But I want to hide this button when it clicked.
I have an ng-click method on button click.
I tried to hide it like this :-
$(this).hide();
The above solutions doesn't work & i also want some solution which is not jquery based.
HTML
<button class="btn-small" ng-click="updateData('contactinformation')" ng-show="contactinformationform.$dirty">Update</button>
CODE
$scope.updateData = function (category) {
switch (category) {
case 'basicinformation':
$scope.categorynewdata = $scope.data.basicinformation[0];
break;
case 'contactinformation':
$scope.categorynewdata = $scope.data.contactinformation[0]
break;
}
var query = {
category: category
};
Patients.updateData().save(query).$promise.then(function (data) {
alert('Data updated successfully..!');
});
}
You can use ng-hide in your button like this
Define scope variable (Like flag) so that you can decide when to hide/show button.
<button ng-click="btnClicked()" ng-hide="hideMe">Submit</button>
Controller
// Initialize hideMe variable
$scope.hideMe = false;
$scope.btnClicked = function() {
/* your code */
$scope.hideMe = true;
}
You can Try like this
Working Demo
html
<div ng-app='myApp' ng-controller="ArrayController">
<form>
<input type="text" ng-model="name" ng-change='flag=false' />: Name
<br>
<input type="text" ng-model="age" ng-change='flag=false' />: Age
<br>
<button class="btn-small" ng-click="updateData('contactinformation')" ng-hide='flag'>Update</button>
</form>
</div>
script
var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
$scope.name = 'Manu';
$scope.age = '21';
$scope.flag = true;
$scope.updateData = function (value) {
$scope.flag = true;
}
});

Categories

Resources