ng-bind for input on button click - angularjs

I use a button to hide/show (toggle) a div:
HTML
<button type="button" ng-click="toggleBuilder()" class="btn btn-primary">Hide Div queryBuilder</span></button>
<input type="text" class="form-control" id="searchField" ng-model="output"/>
<div class="queryBuilder" ng-hide="builder"></div>
JS
$scope.builder = true;
$scope.toggleBuilder = function() {
$scope.builder = $scope.builder === false ? true : false;
};
Now I would like to achieve that if the DIV is hidden, the input has no binding with the "output". If the DIV is shown, the input should have the binding with "output".
Thank you for your tips

Based on your comments, it sounds like you want to disable the input field when the div is visible. You can accomplish this by adding an ng-disabled on the input element, and binding the input to a separate variable from output, and assigning output to the bound variable when the toggle function is called, like so:
<button type="button" ng-click="toggleBuilder()" class="btn btn-primary">Hide Div queryBuilder</span></button>
<input type="text" class="form-control" id="searchField" ng-model="searchTerm" ng-disabled="!builder"/>
<div class="queryBuilder" ng-hide="builder"></div>
And
$scope.builder = true;
$scope.toggleBuilder = function() {
$scope.builder = $scope.builder === false ? true : false;
// set the bound variable if the builder is hidden
$scope.searchTerm = $scope.builder ? $scope.searchTerm : $scope.output;
};

<button type="button" ng-click="toggleBuilder()" class="btn btn-primary">Hide Div queryBuilder</span></button>
<input type="text" class="form-control" id="searchField" ng-model="output"/>
<div class="queryBuilder" ng-hide="builder">{{output}}</div>
This should work, even when the div is hidden, typing into the textfield will still update the scope property output. the ng-model directive will implicitly create a scope property called output when it doesn't find one on the scope.
It's important to note that the value is being stored/updated in the controller, not in your view, you could have a million {{output}} bindings, they would all show the same value as you type into your textfield, so even if your div is hidden, it just hides the output, but that doesn't prevent it from being updated, as this happens in the controller.
The {{output}} (or ng-bind="output") will just show the value of the output scope property.

Related

toggling "ng-hide" property with condition on button click

<input ng-model="email" type="text" class="marginHalf" ng-hide="email==''" readonly>
When on edit button click, Show this so user ca add an email.
You need to have a flag in your controller to toggle on and off when your edit button is clicked.
$scope.editMode = false;
$scope.onEditButtonClick = function(){
$scope.editMode = true;
}
then you use a condition that checks this variable but I recommend using ng-if instead.
<input ng-model="email" type="text" class="marginHalf" ng-if="editMode" readonly>
Here is the difference between ng-if and ng-show/ng-hide.

ngClick does not fire inside label tag

I am trying to fire a click event to toggle show password. That's my code:
HTML
<div class="show-password" ng-click="toggleShowPassword();">
<i class="ion-ios-eye-outline" ng-show="!showPassword"></i>
<i class="ion-ios-eye" ng-show="showPassword"></i>
</div>
<label>
<input type="password" ng-model="myPassword" ng-show="!showPassword">
<input type="text" ng-model="myPassword" ng-show="showPassword">
</label>
JS
$scope.showPassword = false;
$scope.toggleShowPassword = function() {
$scope.showPassword = !$scope.showPassword;
}
The problem is: Outside of <label>, the funcition works fine (above). But if I place the <div class="show-password"> inside of <label>, the function toggleShowPassword() just won't work.
Should I really place the div insde of label ou just leave it this way? (It's working anyway, but it does not feel right).
Is there another way to achieve this function?

Fire a method when click an Enter key

<form novalidate name="frm1" autocomplete="off">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<button ng-click="MyFunc()">Next Step</button>
</div>
</form>
Can you tell me how to fire MyFunc() method when click the enter key.On the above form where there is no submit button. Thanks in advance.
Try this:
<input ng-keyup="$event.keyCode == 13 ? MyFunc() : null" >
At form level you can use this:
<form ng-submit="myFunc()" ...>
I have written below mentioned directive and it works.
Directive :
angular.module('app.directives')
.directive('ngEnter', function () { //a directive to 'enter key press' in elements with the "ng-enter" attribute
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 13) {
scope.$apply(function () {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
})
HTML
<form novalidate name="frm1" autocomplete="off">
//UI elements
<input name="userName" type="text" ng-enter="MyFunc()"/>
<div class="col-sm-3 col-sm-offset-6">
<button ng-click="MyFunc()">Next Step</button>
</div>
</form>
Simply write (keyup.enter)="your_function_name()" in your html file in same way you write (click).
Below is a code snippet.
<input type="text" [(ngModel)]="modelSearchedData" (keyup.enter)="getModelList()">
What you should do is binding your function on submit event instead of enter key. You should not focus on enter, because for exemple on the iPhone there is a keyboard button to execute form, which behave like enter but is not enter event ... and the iPhone is just one exemple :D
So you should change your <button> by an input <type="submit"/>
This way enter key will automatically fire the form submit event.
Then in your submit event, return false; to prevent HTML action (which send the form) and execute your code.
HTML
<form novalidate name="frm1" autocomplete="off">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<input type="submit" value="Next Step" />
</div>
</form>
JS
$('form').submit(function () {
MyFunc();
return false;
});
I hope this answer your question.
PS : you can use ng-submit instead of jQuery selector, if you do not want to use jQuery.
I found a solution that does not require a directive. I was already using ng-change to capture each keypress and perform a search, but clicking Enter would throw my SharePoint page into Edit mode. SharePoint doesn't let you access the form tag, so most of these solutions didn't work for me.
This solution was much simpler and kept my code in the same place, I have an ng-change AND an ng-keypress event that point to the same event handler, vm.txtSearchChange():
HTML
<input id="txtSearch" type="text" style="width: 400px;" ng-change="vm.txtSearchChange()"
ng-keypress="$event.keyCode == 13 ? vm.txtSearchChange($event) : null"
ng-model="vm.Search" ng-model-options="{debounce: 200}"/>
Note the ng-change event does not pass the $event attribute, and handles the legitimate key presses, while the ng-keypress event is only for the enter key.
SCRIPT
vm.txtSearchChange = function ($event) {
if ($event) {
$event.preventDefault();
return;
}
console.log("Search: " + vm.Search);
vm.showResults();
} // end vm.txtSearchChange
When $event is not null, it's the enter key, we call preventDefault() and don't process further. When $event is null, it's a valid key, and we pass it along to vm.showResults() for processing.
Most of the answers here involve additional workarounds that simply are not needed, you can work with the standard form submission by making these two small changes and the Enter key will function as desired.
Move the ng-click from the button to the form, and make it an ng-submit
Add a type="submit" to the button
For more complex forms with multiple buttons you might need to try some of the workarounds, but for the majority of cases this will work.
<form novalidate name="frm1" autocomplete="off" ng-submit="MyFunc()">
//UI elements
<div class="col-sm-3 col-sm-offset-6">
<button type="submit">Next Step</button>
</div>
</form>
<input type="text" name="Inputvalue" id="Inputvalue" ng-change="EnableDisableCheckButton()" ng-model="enteredInputValue" ng-disabled="isDisabledInputvalueTextbox" ng-blur="" data-ng-keypress="onEnterKeyPress($event)" />
<button type="button" class="btn btn-primary" ng-disabled="isDisabledCheckButton" ng-click="ValidateInputvalue()">Check</button>
And in your JavaScript file, add below:
$scope.onEnterKeyPress = function (event) {
if (event.charCode == 13) //if enter is hot then call ValidateInputvalue().
$scope.ValidateInputvalue();
}
This example worked for me:
HTML Code:
<input matInput type="text" [(ngModel)]="searchString" ng-change="startSearch()" ng-keypress="$event.keyCode == 13 ? startSearch($event) : null">
Typescript:
#HostListener('document:keypress', ['$event'])
startSearch(event: KeyboardEvent) {
if (event.code === "Enter") {
//Code that you need to run
}
}
https://go.tiny.cloud/blog/angular-5-tutorial-step-step-guide-first-angular-5-app/

AngularJS: Required form field not woking with ng-click submit

<div ng-app>
<div ng-controller="Ctrl">
<form ng-submit="submit() ">
<textarea ng-model="text" required></textarea>
<div ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</div>
<button type="submit" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</button>
</form>
{{list}}
</div>
</div>
I want to submit an Angular form with a custom div button but when I do it like above, the "required" statements are not taken into account like it is done for the button.
When the textarea is empty the first button runs the submit() function anyway.
Is it possible to have the same behavior as the button ?
Here is a JsFiddle illustrating this:
http://jsfiddle.net/xKkvj/55/
I think you should be using an input rather than a div, eg:
<input type="submit" ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</input>
I've tested it on your jsFiddle, and it works fine.
If you really must use a <div>, use it to wrap the <input>
UPDATE
It looks like you can't use anything other than an input or a button as that is what ngForm listens to for form submission. You could either extend ngForm or you could use a hidden button and trigger that from your div like so:
<div onClick="document.getElementById('hiddenButton').click();" style="background-color:#0000ff;cursor:pointer;width:100px;">Create !</div>
<button id='hiddenButton' type="submit" style="display:none;">Create !</button>
jsFiddle here. Hopefully this'll do the trick for you.
If you want to submit form from a div element, then you should manually test if form is valid in your submit handler:
function sumbit() {
if (form.$invalid) {
return;
}
// Other code...
}
The point is that when you submit your form via <input type="submit"/>, then form validation check is performed internally & form handler do not invoked in case of invalid form.
UPDATE
Your jsfiddle form handler should look like:
$scope.submit = function () {
if ($scope.submitCreateSurveyForm.$invalid) {
return;
}
if ($scope.text) {
$scope.list.push($scope.text);
$scope.text = '';
}
console.log("sent");
};

Configure Angular to re-evaluate on blur instead of keypress

By default, it seems that Angular reevaluates its binding from a particular DOM element (e.g Text Input) to the underlying scope property on keypress or paste - i.e, whenever the value in the text input changes.
Is it possible to make it only refresh the binding on blur? I.e. do something like:
<div ng-app>
<div ng-controller="ctrl">
<input type="text" ng-model="base" ng-update-type="blur"/>
<input type="text" />
<span ng-bind="doubled()" />
</div>
</div>
Take the following JS fiddle:
http://jsfiddle.net/f76dW/
I would like the doubled span to only update when I move the focus out of the first input
You can use ng-blur and a dummy variable (base_ in this case) to achieve that effect: http://jsfiddle.net/f76dW/1/
Template
<input type="text" ng-model="base_" ng-blur="updateBase()" />
Controller
function ctrl($scope) {
$scope.base = $scope.base_ = 1000;
$scope.updateBase = function () {
$scope.base = $scope.base_;
};
$scope.doubled = function() {
return $scope.base * 2;
}
}
Use ng-model options. Using a blur hack is tricky, because a blur may not be a change.
<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options={updateOn: 'blur'}"/>

Resources