Angular JS - Focus on dyamically created text box - html

I have a table in which one item is editable. On clicking that item, the text changes to a text box and it can be edited. The issue is, on clicking the text, the text changes to textbox but I'm not able to focus on the textbox.
This is the code
JS
$scope.togglePrice = function (item) {
item.showUpdatePrice = true;
}
HTML
<a ng-click="togglePrice(item)" ng-hide="item.showUpdatePrice" style="text-decoration:underline; cursor:pointer;">{{item.sellingPrice | currencyFormat}}</a>
<input id="updatePriceId" ng-model="item.sellingPrice" class="form-control" ng-class="{'errorClass': showPriceError}" ng-show="item.showUpdatePrice" ng-blur="saveUpdatedPrice(item)" type="text" placeholder="Enter Price">
Edit
<tbody ng-repeat="item in shoppingItems">
<tr>
<td class="priceDiv">
<div>
<a ng-click="togglePrice(item)" ng-hide="item.showUpdatePrice" style="text-decoration:underline; cursor:pointer;">{{item.sellingPrice | currencyFormat}}</a>
<input ng-model="item.sellingPrice" auto-focus class="form-control" ng-class="{'errorClass': showPriceError}" ng-show="item.showUpdatePrice" ng-blur="saveUpdatedPrice(item)" type="text" placeholder="Enter Price">
</div>
</td>
</tr>
</tbody>

You should make a small change to your method and should add one directive to achieve your solution.
$scope.togglePrice = function (item) {
item.showUpdatePrice = !item.showUpdatePrice;
}
In this solution, on click on the text-boxes, the respective textbox gets focussed, and on blur or clicking outside, it gets unfocussed.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
Click to focus on Below TextBoxes:
<table ng-controller="myCtrl">
<tbody ng-repeat="item in shoppingItems">
<tr>
<td class="priceDiv">
<div>
<a ng-click="togglePrice(item)" ng-hide="item.showUpdatePrice" style="text-decoration:underline; cursor:pointer;">{{item.sellingPrice}}</a>
<input ng-model="item.sellingPrice" auto-focus class="form-control" ng-class="{'errorClass': showPriceError}" ng-show="item.showUpdatePrice" ng-blur="saveUpdatedPrice(item)" type="text" placeholder="Enter Price" focus-me="item.showUpdatePrice">
</div>
</td>
</tr>
</tbody>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.togglePrice = function (item) {
item.showUpdatePrice = !item.showUpdatePrice;
}
$scope.shoppingItems = [
{
"showUpdatePrice" : false,
"sellingPrice" : "10"
},
{
"showUpdatePrice" : false,
"sellingPrice" : "20"
},
{
"showUpdatePrice" : false,
"sellingPrice" : "30"
},
]
});
app.directive('focusMe', ['$timeout', '$parse', function ($timeout, $parse) {
return {
link: function (scope, element, attrs) {
var model = $parse(attrs.focusMe);
scope.$watch(model, function (value) {
if (value === true) {
$timeout(function () {
element[0].focus();
});
}
});
element.bind('blur', function () {
scope.$apply(model.assign(scope, false));
});
}
};
}]);
</script>
</body>
</html>
PLEASE RUN THE ABOVE SNIPPET
Here is a working DEMO

Update your code with below code, may be it helps you. It will add a unique id to your inputs according to index. So you can simply access them using most efficient javascript selector.
Change your javascript to
$scope.togglePrice = function (item, buttonClicked) {
item.showUpdatePrice = true;
setTimeout(function(){
document.getElementById(buttonClicked).focus();
});
}
And in html
<tbody ng-repeat="item in shoppingItems">
<tr>
<td class="priceDiv">
<div>
<a ng-click="togglePrice(item, $index)" ng-hide="item.showUpdatePrice" style="text-decoration:underline; cursor:pointer;">{{item.sellingPrice | currencyFormat}}</a>
<input id='{{$index}}' ng-model="item.sellingPrice" auto-focus class="form-control" ng-class="{'errorClass': showPriceError}" ng-show="item.showUpdatePrice" ng-blur="saveUpdatedPrice(item)" type="text" placeholder="Enter Price">
</div>
</td>
</tr>
</tbody>
Try this May be it helps you. Thanks

Related

adding element to parent from directive

In order to disable the auto complete of chrome in forms, i want to create angular directive which add dummy input element
my code is
`angular.module("noc.components").directive('customInput', function ($compile) {
"use strict";
return {
restrict:'E',
template:'<input>',
replace:true,
link: function(scope, elem) {
//scope.type = attrs.type || 'email';
var el = angular.element('<input name={{type}} style="display: none">');
//var type = elem[0].name;
$compile(el)(scope);
elem.parent().append(el);
}
};
});`
and the html is
<div class="form-group">
<label for="setupWizardUserStepEmail">Email Address</label>
<custom-input class="form-control"
id="setupWizardUserStepEmail"
ng-model="setupRequest.userRequest.email"
name="email"
ng-required="true"
noc-validation="email"
autocomplete="off"
autofocus="true">
</div>
however the injected html isnt in the parent - i want it to be above the directive
how can i do it?
I was able to solve my own problem in the end:
I changed it to elem.parent().prepend(el);

Angular Checkboxes "Select All" functionality with only one box selected initially

I have a form that contains 3 checkboxes: "Select All", "Option 1", and "Option 2".
<form id="selectionForm">
<input type="checkbox" ng-model="selectAll" >Select all
<br>
<input type="checkbox" ng-checked="selectAll" checked>Option 1
<br>
<input type="checkbox" ng-checked="selectAll">Option 2
</form>
On the initial page load I want only Option 1 to be checked. And then if the Select All checkbox gets checked it should automatically check Option 1 and Option 2 so all are selected.
The problem is on the initial page load the ng-checked="selectAll" gets evaluated which overrides my attempt to initially check only Option 1 (selectAll = false initially), so nothing is selected.
This seems like a simple problem to solve, but I can't figure out a solution... Thanks in advance for any insights or advice!
Another way to go about it is to use a model for the options, set default selection in the model and have your controller handle the logic of doing select all.
angular.module("app", []).controller("ctrl", function($scope){
$scope.options = [
{value:'Option1', selected:true},
{value:'Option2', selected:false}
];
$scope.toggleAll = function() {
var toggleStatus = !$scope.isAllSelected;
angular.forEach($scope.options, function(itm){ itm.selected = toggleStatus; });
}
$scope.optionToggled = function(){
$scope.isAllSelected = $scope.options.every(function(itm){ return itm.selected; })
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> </script>
<div ng-app="app" ng-controller="ctrl">
<form id="selectionForm">
<input type="checkbox" ng-click="toggleAll()" ng-model="isAllSelected">Select all
<br>
<div ng-repeat = "option in options">
<input type="checkbox" ng-model="option.selected" ng-change="optionToggled()">{{option.value}}
</div>
</form>
{{options}}
</div>
Try this:
<form id="selectionForm">
<input type="checkbox" ng-model="selectAll" >Select all
<br>
<input type="checkbox" ng-checked="selectAll || option1" ng-init="option1=true" ng-model="option1">Option 1
<br>
<input type="checkbox" ng-checked="selectAll">Option 2
</form>
I like to use an ng-repeat for clarity on showing what you're selecting/un-selecting, basically you end up with a nice little object to base it all on, and adding to it is just easier.
Here's a Plunker
*Also notice how you can achieve allSelected? with a loop func and not a ton of html, and I'm sure this can be done with less spaghetti but it works *
app.controller('MainCtrl', function($scope) {
$scope.allSelected = false;
$scope.checkboxes = [{label: 'Option 1',checked: true}, {label: 'Option 2'}}}];
$scope.cbChecked = function(){
$scope.allSelected = true;
angular.forEach($scope.checkboxes, function(v, k) {
if(!v.checked){
$scope.allSelected = false;
}
});
}
$scope.toggleAll = function() {
var bool = true;
if ($scope.allSelected) {
bool = false;
}
angular.forEach($scope.checkboxes, function(v, k) {
v.checked = !bool;
$scope.allSelected = !bool;
});
}
});

How to control ng-repeat divs from ng-repeat inputs

So, just getting started in Angular and it's pretty tricky, coming from a pretty simple JS and jQuery background. Here's what I'm trying to do. I have a "tag template" that has a couple categories and then some sub-tags contained within. I have defined these as an object, with the idea that the object/file can be called via file request and manipulated, etc.
I have loaded labels and tag category inputs dynamically by using a factory service and a controller with ng-repeat. Likewise, I have deposited the subtags into another div on page2 (using jQuery mobile page swiping). I'd like to use the checkbox state of the category tags to show/hide the sub-tags on page2.
I have tried dozens of things and searched all over stackexchange, the net, etc, but is simple and straightforward and similar enough for me to get it working. If someone can point me in the right direction, that would be great. Keep in mind that my next step is to add a button on page 1 to add a new category, and buttons on page 2 to add sub-tags to the sub-tag categories.
Finally, I have one more weird thing to report. If I only have two pages in my DOM, I have some weird behavior when loading the page. If I load from page 1, the tag checkboxes do not function, and I see a slight fattening of the border of the labels. If I swipe left to page 2 and reload from this page, the borders of the labels are thin and the checkboxes function. Cannot track down why this would be happening. My hacky workaround is to add an empty page zero and then changepage immediately to page one, but this is far from ideal. Any thoughts on that would be appreciated as well.
Here it is:
HTML
<!-- Angular version -->
<button class="ui-btn" onclick="selectTemplate();">My Template</button>
<form>
<div data-role="controlgroup">
<fieldset data-role="controlgroup">
<div ng-controller="templateCtrl">
<label
class="ui-checkbox"
ng-style="{backgroundColor: '{{tagCat.color | bgColor}}'}"
ng-repeat="tagCat in template"><input type="checkbox"
class="ui-checkbox"
id="{{tagCat.name}}"
ng-model="clicked"
ng-click="click();"
/>{{tagCat.name}}</label>
<div ng-repeat="tagCat in template">{{cb}} {{tagCat.name}} hallo</div>
</div>
</fieldset>
</div>
<div style="display:none" class="flashNotification"></div>
</form>
</div>
<div data-role="page" id="two">
<button class="ui-btn" onclick="selectTemplate();">My Template</button>
<form>
<div data-role="controlgroup">
<div ng-controller="templateCtrl">
<div ng-repeat="tagCat in template" ng-show="clicked" class="{{tagCat.name}}">{{tagCat.name}}
<fieldset data-role="controlgroup">
<label class="ui-checkbox"
ng-repeat="item in tagCat.items"
ng-style="{backgroundColor: '{{tagCat.color | bgColor}}'}"
for="item.name">{{tagCat.color | bgColor}}
<input class="ui-checkbox"
name="{{item.name}}"
id='{{item.name}}'
type="checkbox" />{{item.name}}</label>
</fieldset>
</div>
</div>
</div>
<div style="display:none" class="flashNotification"></div>
</form>
</div>
</div>
JS for jQuery Mobile
$(document).ready(function() {
// addTemplateItems(tagTemplate); // not necessary with Angular
// $.mobile.changePage('#two', { transition: 'none' }); // required or checkboxes don't work on load
$.mobile.changePage('#one', { transition: 'none' });
// // $("[data-role=controlgroup]").controlgroup("refresh");
// set up page nav
$(document).delegate('.ui-page', "swipeleft", function(){
var $nextPage = $(this).next('[data-role="page"]');
var $prevPage = $(this).prev('[data-role="page"]');
console.log("binding to swipe-left on "+$(this).attr('id') );
// swipe using id of next page if exists
if ($nextPage.length > 0) {
$.mobile.changePage($nextPage, { transition: 'slide' });
} else {
var message = 'tagged!';
// save tags here
flashNotify(message);
console.log('fire event!');
$('#flashNotification').promise().done(function () {
$('#group1').hide();
$('#group2').hide();
$('.ui-btn').hide();
// addTemplateItems(tagTemplate);
$.mobile.changePage($prevPage, { transition: 'none' });
captureImage();
});
}
}).delegate('.ui-page', "swiperight", function(){
var $prevPage = $(this).prev('[data-role="page"]');
console.log("binding to swipe-right on "+$(this).attr('id') );
// swipe using id of next page if exists
if ($prevPage .length > 0) {
$.mobile.changePage($prevPage, { transition: 'slide', reverse : true });
} else {
alert('no backy backy!');
}
});
// $("input[type='checkbox']").checkboxradio().checkboxradio("refresh");
});
JS for Angular App
var app = angular.module('STL', []);
app.factory('TagTemplate', [function () {
var TagTemplate = {};
var tagTemplate = {
family: {
name: "family",
description: "These are your family members.",
color: "red",
items: [
{
name: "Joe"
},
{
name: "Mary"
},
{
name: "Jim"
}
]
},
design: {
name: "design",
description: "Different types of design notes.",
color: "blue",
items: [
{
name: "inspiring"
},
{
name: "fail"
},
{
name: "wayfinding"
},
{
name: "graphics"
}
]
},
work: {
name: "work",
description: "Stuff for work.",
color: "green",
items: [
{
name: "whiteboard"
},
{
name: "meeting"
},
{
name: "event"
}
]
}
};
TagTemplate = tagTemplate;
return TagTemplate;
}])
// Controller that passes the app factory
function templateCtrl($scope, TagTemplate) {
$scope.template = TagTemplate;
$scope.click = function(model) {
console.log(this.checked, this.tagCat.name);
}
}
app.filter('bgColor', function () {
return function (color) {
// console.log(color, $.Color(color).lightness(.05).toHexString(.05));
// var rgba = $.Color(color).alpha(.05);
return $.Color(color).lightness(.97).toHexString();
}
})
For the main part, success!
I found a jsfiddle that gave me a good base for experimenting. After some playing, I realized that I just have to create a show property within each of the categories in my data service model, and then assign the ng-model to that property to control it.
I had to do it slightly differently in my own code, but the understanding gained from the following jsfiddle led me to the answer:
http://jsfiddle.net/Y43yP/
HTML
<div ng-app ng-controller="Ctrl">
<div class="control-group" ng-repeat="field in customFields">
<label class="control-label">{{field}}</label>
<div class="controls">
<input type="text" ng-model="person.customfields[field]" />
<label><input type="checkbox" ng-model="person.show[field]" /></label>
</div>
</div>
<button ng-click="collectData()">Collect</button><button ng-click="addField()">Add Field</button><br/><br/>
<em>Booleans</em>
<div ng-repeat="field in customFields">
<p>{{field}}: {{person.show[field]}}</p>
</div>
<em>Show/Hide</em>
<div ng-repeat="field in customFields">
<p ng-show="person.show[field]">{{field}}: {{person.customfields[field]}}</p>
</div>
</div>
JS
function Ctrl($scope) {
$scope.customFields = ["Age", "Weight", "Height"];
$scope.person = {
customfields: {
"Age": 0,
"Weight": 0,
"Height": 0
},
show: {
"Age": false,
"Weight": false,
"Height": false
}
};
$scope.collectData = function () {
console.log($scope.person.customfields, $scope.person.show);
}
$scope.addField = function () {
var newField = prompt('Name your field');
$scope.customFields.push(newField);
}
}
Still having the checkbox issue but I'll open a separate issue for that if I can't figure it out.
Thanks.

Edit In Place Content Editing

When using ng-repeat what is the best way to be able to edit content?
In my ideal situation the added birthday would be a hyperlink, when this is tapped it will show an edit form - just the same as the current add form with an update button.
Live Preview (Plunker)
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Custom Plunker</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css"
rel="stylesheet">
</head>
<body ng-app="birthdayToDo" ng-controller="main">
<div id="wrap">
<!-- Begin page content -->
<div class="container">
<div class="page-header">
<h1>Birthday Reminders</h1>
</div>
<ul ng-repeat="bday in bdays">
<li>{{bday.name}} | {{bday.date}}</li>
</ul>
<form ng-show="visible" ng-submit="newBirthday()">
<label>Name:</label>
<input type="text" ng-model="bdayname" placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" ng-model="bdaydate" placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
</form>
</div>
<div id="push"></div>
</div>
<div id="footer">
<div class="container">
<a class="btn" ng-click="visible = true"><i class="icon-plus"></i>Add</a>
</div>
</div>
</body>
App.js:
var app = angular.module('birthdayToDo', []);
app.controller('main', function($scope){
// Start as not visible but when button is tapped it will show as true
$scope.visible = false;
// Create the array to hold the list of Birthdays
$scope.bdays = [];
// Create the function to push the data into the "bdays" array
$scope.newBirthday = function(){
$scope.bdays.push({name:$scope.bdayname, date:$scope.bdaydate});
$scope.bdayname = '';
$scope.bdaydate = '';
};
});
You should put the form inside each node and use ng-show and ng-hide to enable and disable editing, respectively. Something like this:
<li>
<span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
</form>
</li>
The key points here are:
I've changed controls ng-model to the local scope
Added ng-show to form so we can show it while editing
Added a span with a ng-hide to hide the content while editing
Added a ng-click, that could be in any other element, that toggles editing to true
Changed ng-submit to toggle editing to false
Here is your updated Plunker.
I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.
The example is available here http://plnkr.co/edit/EsW7mV?p=preview
Here goes the code:
app.controller('MainCtrl', function($scope) {
$scope.updateTodo = function(indx) {
console.log(indx);
};
$scope.cancelEdit = function(value) {
console.log('Canceled editing', value);
};
$scope.todos = [
{id:123, title: 'Lord of the things'},
{id:321, title: 'Hoovering heights'},
{id:231, title: 'Watership brown'}
];
});
// On esc event
app.directive('onEsc', function() {
return function(scope, elm, attr) {
elm.bind('keydown', function(e) {
if (e.keyCode === 27) {
scope.$apply(attr.onEsc);
}
});
};
});
// On enter event
app.directive('onEnter', function() {
return function(scope, elm, attr) {
elm.bind('keypress', function(e) {
if (e.keyCode === 13) {
scope.$apply(attr.onEnter);
}
});
};
});
// Inline edit directive
app.directive('inlineEdit', function($timeout) {
return {
scope: {
model: '=inlineEdit',
handleSave: '&onSave',
handleCancel: '&onCancel'
},
link: function(scope, elm, attr) {
var previousValue;
scope.edit = function() {
scope.editMode = true;
previousValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
scope.save = function() {
scope.editMode = false;
scope.handleSave({value: scope.model});
};
scope.cancel = function() {
scope.editMode = false;
scope.model = previousValue;
scope.handleCancel({value: scope.model});
};
},
templateUrl: 'inline-edit.html'
};
});
Directive template:
<div>
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
<button ng-click="cancel()" ng-show="editMode">cancel</button>
<button ng-click="save()" ng-show="editMode">save</button>
<span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
<span ng-hide="editMode" ng-click="edit()">{{model}}</span>
<a ng-show="showEdit" ng-click="edit()">edit</a>
</span>
</div>
To use it just add water:
<div ng-repeat="todo in todos"
inline-edit="todo.title"
on-save="updateTodo($index)"
on-cancel="cancelEdit(todo.title)"></div>
UPDATE:
Another option is to use the readymade Xeditable for AngularJS:
http://vitalets.github.io/angular-xeditable/
I've modified your plunker to get it working via angular-xeditable:
http://plnkr.co/edit/xUDrOS?p=preview
It is common solution for inline editing - you creale hyperlinks with editable-text directive
that toggles into <input type="text"> tag:
<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
{{bday.name || 'empty'}}
</a>
For date I used editable-date directive that toggles into html5 <input type="date">.
Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

textbox disable in knockout

I have a table like below:
<tbody data-bind="foreach: tasks">
<tr>
<td>
<span data-bind="text: goal" />
</td>
<td>
<input type="text" data-bind="value: note ,
disable: !($data.isAllowedForMember)" />
</td>
</tr>
</tbody>
I want to make note textbox disable when isAllowedForMember = false. But everytime its making note disable(wheather isAllowedForMember = true or false).
Here is my viewmodel
//viewmodel
function GoalSheetViewModel() {
self.tasks = ko.observableArray([]); //tasklist
self.note = ko.observable();
self.isAllowedForMember = ko.observable();
self.IsAllowedToChange = function () {
$.ajax({
success: function (results) {
self.isAllowedForMember(results.d);
},
})
};
};
You should unwrap observable if you use it in condition:
<input type="text" data-bind="value: note , disable: !$parent.isAllowedForMember()" />
The following article can help you to learn some useful things about knockout: http://www.knockmeout.net/2011/06/10-things-to-know-about-knockoutjs-on.html
EDIT:
isAllowedForMember is member of parent context so you should use $parent object to access it:
<input type="text" data-bind="value: note , disable: !$parent.isAllowedForMember()" />
As Artem said you need to unwrap the observable, but even better to use a computed with a name saying what the business rule means
like
this.readonlyMember = ko.computed(function() {
return this.isAllowedForMember();
}, this);
But you also have a releation problem with your model since you get
ReferenceError: isAllowedForMember is not defined