Angularjs keep the focus on a field after ng-click? - javascript

I try to figure out how I can keep the focus on an input field in angularjs after I click on a button.
My goal is to prevent my mobile to hide his keyboard right after I click on the + button. I want to keep the focus on input choice.
Like this the user can add a new choice without the need to click again on my input.
<div id="demo" ng-app="Foobar">
<div ng-controller="DemoCtrl">
<input type="text" ng-model="title" placeholder="title" />
<input type="text" ng-model="choice" placeholder="choice" />
<button ng-click="addChoice(choice)">+</button>
{{choices}}
</div>
</div>
angular.module('Foobar', [])
.controller('DemoCtrl', ['$scope', function ($scope) {
$scope.choices = [];
$scope.addChoice = function (choice) {
$scope.choices.push(choice);
};
}]);
http://jsfiddle.net/gbg09bto/
What is the best strategy ? (directive, ng-focus)

simplest thing is do it by plain javascript
to do it
in html // put a id attribute
<input type="text" id="choice" ng-model="choice" placeholder="choice" />
in controller function
$scope.addChoice = function (choice) {
$scope.choices.push(choice);
document.getElementById("choice").focus(); // get the element by id & focus the input
};
here is the updated Fiddle

Related

on-click event does not make the other field editable in one-click?

<!--Below is the html code-->
<div ng-init="InitializeFields()">
<input type="text" on-click="makeOtherReadOnly('1')"
readonly="show_or_not_first"/>
<input type="text" on-click="makeOtherReadOnly('2')" readonly="show_or_not_second"/>
</div>
// Now inside javascript
$scope.makeOtherReadOnly=function(number){
if(number==='1'){
show_or_not_second=true;
show_or_not_first=false;
show_or_not_second=true;
}else if(number==='2'){
show_or_not_first=true;
show_or_not_second=false;
}
};
$scope.Initializer=function(){
show_or_not_first=false;
show_or_not_second=false;
}
$scope.Initializer();
the problem that I am facing is as I click on the input field, it should turn the other field to readonly after pafe gets loaded and we have either field clicked, but it requires two click...
Every help is appreciated.
Try changing on-click to ng-click.
You need to correct few things ion your code :
change on-click to ng-click, So your function can be called from HTML.
Change readonly to ng-readonly, So you can utilize $scope property
In your ng-init, I guess you need to call Initializer() method to initialize default value.
Further just to make 2 input box readonly, you can chieve this by 1 flag. and no string comparison.
Simple Demo :
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.makeOtherReadOnly = function(boolValue) {
console.log(boolValue);
$scope.data.first = boolValue;
};
$scope.Initializer = function() {
$scope.data = {
first: false
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-init="Initializer()">
First: <input type="text" ng-click="makeOtherReadOnly(false)"
ng-readonly="data.first" />
Second: <input type="text" ng-click="makeOtherReadOnly(true)"
ng-readonly="!data.first" />
</div>
</div>
There are two scopes here
javascript and angular
sometimes inside ng-click, javqascript function don't work
so change on-click to ng-click.

how to not validate hidden field in ng-click?

when user click on submit button i am validating form, using ng-click i am calling function, in this function i am passing form1.$invalid,based on this variable , i am putting condition, if condition true, validate function will call, here problem is mobile is hidden field, this hidden field also checking validation.how can skip or not validate mobile field hidden status, I tried bellow code.
html
----
<form name="form1" novalidate>
<input ng-show="user" type="text" name="user" ng-model="frm1.user" />
<p ng-show="form1.user.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p>
<input ng-show="mobile" type="text" name="mobile" ng-model="frm1.mobile" />
<p ng-show="form1.mobile.$error.required"><span ng-show="errorMsgShow" ng-required="true">{{requiredMsg}}</span></p>
<button ng-click="SubmitForm(regForm.$invalid);">submit</button>
</form>
Script----
$scope.SubmitForm = function(val){
$scope.user= true;
$scope.mobile = false;
if (if(val ===true){
$scope.validation();
}
}
$scope.validation = function(){
$scope.requiredMsg="input fieldis required";
}
I suggest better approach will be taking the mobile input out of the form when it's unnecessary using ng-if rather than just hide it with ng-show.
Ng-if will make sure the input is not rendered in the DOM tree when the condition is false, therefore, there will be no validation triggered.
You can do some research on differences between ng-if and ng-show to have better understanding about these two directives.
Try ng-if to avoid validation.If you want mobile to skip validation then make ng-if as false using expression.
syntax: ng-if="expression"
go to this link for further info
https://docs.angularjs.org/api/ng/directive/ngIf
for difference between ng-if and ng-hide/ng-show refer the below link
what is the difference between ng-if and ng-show/ng-hide
Some observations :
Instead of using ng-show to hide and show the inputs just use <input type="hidden"... > element for mobile field.
No need to use variable $scope.user and $scope.mobile to hide and show the inputs.
Add the required attribute in the user input field not on mobile input field as you don't want to validate mobile field.
Use SubmitForm(form1.$invalid) instead of SubmitForm(regForm.$invalid) as your form name is form1 not regForm.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
$scope.SubmitForm = function(val) {
console.log(val);
if(val === true) {
$scope.validation();
}
}
$scope.validation = function() {
$scope.requiredMsg="input fieldis required";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="form1" novalidate>
<input type="text" name="user" ng-model="frm1.user" required/>
<p ng-show="form1.user.$error.required">{{requiredMsg}}</p>
<input type="hidden" name="mobile" ng-model="frm1.mobile" />
<button ng-click="SubmitForm(form1.$invalid);">submit</button>
</form>
</div>

AngularJS Checkbox retain check value when the page reloads

I have a search screen with a checkbox, and want to retain the checkbox selection when the user navigates away and comes back to the screen.
Using the session storage, i am able to retain the value in the model, but the checkbox checked does not display correct based on the model value.
When I search online, it looks like i cannot use ng-model and ng-checked together. But I don't want to use jquery either.
Is it possible to do this with just Angular? Thanks in Advance.
<div class="container" ng-controller="SearchController as vm" data-ng-init="vm.init()">
<form ng-submit="vm.Search()">
<input type="checkbox" id="chkActive" name="chkActive" value="Active" ng-model="vm.searchInput.active" ng-checked="vm.searchInput.active" /> <span>Show Active Records</span>
<button id="searchBtn" type="submit">
</form>
</div>
Angular Controller Code:
vm.searchInput = { active: true};
vm.init = function () {
if ($window.sessionStorage.getItem("Search_Active")) {
vm.searchInput.active = $window.sessionStorage.getItem('Search_Active'); }
}
vm.Search = function () {
$window.sessionStorage.setItem('Search_Active', vm.searchInput.active);
}
I haven't checked it, but I'm sure the first line should read:
vm.searchInput = { active: true};
If the model value is there, you want to bind to it, and you know it's good then why would you need both checked and model? Binding the value to the input is enough. As you can see below, using both is problematic.
angular.module('app', []);
angular.module('app').controller('c', c);
function c() {
var self = this;
self.checked = true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app "app" ng-controller="c as ctrl">
<div>
<label>Checked</label>
<input type="checkbox" ng-model="ctrl.checked" />
<div>
<span>Checked: {{ctrl.checked}}</span>
</div>
</div>
<div>
<label>Checked Trouble</label>
<input type="checkbox" ng-model="ctrl.checked" ng-checked="!ctrl.checked" />
<div>
<span>Checked: {{ctrl.checked}}, !Checked: {{!ctrl.checked}}</span>
</div>
</div>
<div>
<label>Checked Double Trouble</label>
<input type="checkbox" ng-checked="!ctrl.checked" ng-model="ctrl.checked" />
<div>
<span>Checked: {{ctrl.checked}}, !Checked: {{!ctrl.checked}}</span>
</div>
</div>
</div>

change css class on click in angularJs

I am trying to change the CSS class of a div element on click. Below is the code I am trying.
'input-large' should be active by default.
'input-large input-active' should become active on click on username and becomes inactive on clicking somewhere else.
<div class="input-large">
<label class="input-label">Username</label>
<input class="input-field" type="text">
</div>
<div class="input-large input-active">
<label class="input-label">Username</label>
<input class="input-field" type="text">
</div>
Please let me know how to change the DIVs on click
please use ng-click and ng-blur
follow the snippet in :
http://jsfiddle.net/atXAC/11/
<div ng-controller="MyCtrl">
<div ng-class="{'active':hasFocus==true,'inactive':hasFocus==false}">Enter your Name here</div>
<input type="text" ng-model="user.name" ng-click="hasFocus=true" ng-customblur="onBlur()" required id="name"/>
</div>
here goes your js
var myApp = angular.module('myApp', []);
myApp.directive('ngCustomblur', ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr['ngCustomblur']);
element.bind('blur', function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
}
}]);
function MyCtrl($scope) {
$scope.onBlur = function(){
$scope.hasFocus = false;
}
}
please adapt it for your form.. its working
another approach can be to append the css class in onClick handler in your controller.

Get HTML element data in AngularJS script

I am new to AngularJS and trying to design a page which will have two text fields and two radio buttons.
First text field is for current address, followed by radio buttons(one for Yes and second for No), and last component would be permanent address text field. First, user will enter the value in current address text field, after that if user selects yes radio button then it should copy the data from current address to permanent address text field, if user selects No then it should do nothing. Below is the sample code I have written:
*<input type="text" name="cAddress" ng-model="cAddress" required/>
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" required/>*
Below is the script code inside controller:
$scope.copyAddress = function(flag) {
if(flag) {
$scope.pAddress = $scope.cAddress;
}
};
when I tried to print $scope.cAddress and $scope.pAddress values in console then it displayed undefined. Even $scope does not have cAddress and pAddress.
Therefore, the main problem is that I am not getting element data inside AngularJS controller
Please find plunker url:
http://plnkr.co/edit/Ub2VEn01HxwDpnCg4tLi?p=preview
Click on Next to navigate to Second tab, there you will find the yes and no radio button to copy the data.
I have minized the code, please look into it. To understand the flow, you can read the README file.
http://plnkr.co/edit/TzJsZIRxAyTuFdCXLFFV?p=preview
Try using another scope object.
That is, create a scope object and add property to it for each input like,
$scope.myObject = {}; // Empty scope variable
$scope.myObject.cAddress = ""; // initialize your model for the input.
And now you should use this variable for your input.
<input type="text" name="cAddress" ng-model="myObject.cAddress" required/>
Try this. It may help you.
Html code:
<body ng-controller='Maincontroller'>
<input type="text" name="cAddress" ng-model="cAddress" />
<input type="radio" name="opt" ng-click="copyAddress(true)" />
<input type="radio" name="opt" ng-click="copyAddress(false)" />
<input type="text" name="pAddress" ng-model="pAddress" />
</body>
Controller code:
var app = angular.module('main', []);
app.controller('Maincontroller', ["$scope",
function($scope) {
$scope.copyAddress = function(flag) {
if (flag) {
$scope.address1 = $scope.address;
} else {
$scope.address1 = "";
}
};
}
]);

Categories