How to change the content of an Angular field textarea using jQuery - javascript

I am trying to change the color of a textarea in an Angular app using jQuery but it does not work.
What should I do? It says $ is not defined.
HTML:
<body>
<div ng-app="myApp" ng-controller="testController">
<textarea id="abc">abc
</textarea>
</div>
</body>
</html>
Angular js:
var app = angular.module('myApp', []);
app.controller('testController', function($scope, $http) {
var tdVal =$("#abc");
var x = tdVal.innerHTML;
tdVal.html ("<span style='color: rgba(220, 0, 0, 1)'>" + x"</span>");
});

You are not just changing color, but the control itself. If changing color is the intent:
var elem = angular.element('#abc');
elem.css('color', 'rgba(220, 0, 0, 1)');
for value update, angular provides you bind directive.
$scope.value = 'some value'
and in view
<textarea id="#abc" ng-bind="value"></textarea>

Try this, it does work if there are not some other dependincies:
$('#abc').css('color', 'rgba(220, 0, 0, 1)');

it looks like you want to render HTML within textarea tag, which is not allowed by browsers, but what you can do is to use editable div element:
<div id="abc" contenteditable="true"></div>
check out Rendering HTML inside textarea
angular.element by default uses jQueryLight which is limited version og jQuery. You should use ng-style angular directive:
<div id="abc" contenteditable="true">
<span ng-style="{color: 'rgba(220, 0, 0, 1)'}">abc</span>
</div>
or you can assign to ng-style your custom function which will return CSS object, according to your logic.

Related

contenteditable -- How to make only the title to be in block using angularjs

I have a input field which is editable, when I click on that it must give background color as white with in box. Please help me.
I am sharing my code here:
HTML
<div id="section{{section.index}}">
<h2 class="title" contenteditable="true" ng-model="section.title"
onclick="document.execCommand('selectAll',false,null)"
ng-keydown="disable_enter($event)"
ng-change="check_section_title($index)"
maxlength="40">
</h2>
</div>
I am getting like this
**But i need like this **
Custom Directive for contenteditable elements
To make a contenteditable element work with the ng-model directive
and the ngModelController:
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!
</div>
Create a custom directive:
app.directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
The DEMO
angular.module('app', ['ngSanitize'])
.directive('contenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$evalAsync(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html === '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}])
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-sanitize/angular-sanitize.js"></script>
<body ng-app="app">
<form name="myForm">
<p>Click on below div to edit</p>
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
</form>
</body>
For more information, see AngularJS ngModelController API Reference - Custom Control Example
Check this example which give you both your solution max length as well as color changing when textbox selected.
You can use ng-maxlength="3" as well as class to highlight the maxlength comes.
http://jsfiddle.net/gabrielmaldi/5o1uxnx8/
http://jsfiddle.net/ksevksev/YWq7g/
You should use maxlength to your input control instead of div or h1 tags.
Use something like this if you using angular version 1
<input type="text" ng-maxlength="40" />
Use something like this if you using angular2
<input type="text" [maxlength]="40" />
JS Code :
document.getElementById("myInput").style.backgroundColor = "lightblue";
function changeColor() {
var textBoxLength = document.getElementById('myInput').value.length;
if(textBoxLength >= 5){
document.getElementById("myInput").style.backgroundColor = "white";
}
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body ng-app="">
<form name="myForm">
<h1>Type in textbox</h1>
<input name="myInput" id="myInput" ng-model="myInput" ng-maxlength="5" onkeypress="changeColor()">
<h1 ng-if="!myForm.myInput.$valid">The value is too long</h1>
</form>
</body>
</html>
In the above code, i am setting background to lightblue initially , and changing it to white while the characters go beyond 5. but in your case it should be 40.
You cannot use ng-model on h2 tag. You can use an input in conjunction with the h2 tag. Hide the h2 tag on click and enable the input. You can use maxlength to limit the characters to 40 and use ng-maxlength for validations
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.val={};
$scope.val.type="Hello";
$scope.contenteditable=false;
$scope.check_section_title = function() {
$scope.contenteditable=!$scope.contenteditable;
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-require="angular.js#1.5.x" data-semver="1.5.11"></script>
</head>
<body ng-controller="MainCtrl">
<form name="myForm" novalidate>
<div style="padding: 10px">
<div id="section{{section.index}}">
<h2 class="title" ng-click="check_section_title()" ng-if="!contenteditable">{{val.type}}</h2>
</div>
<input name="Hazmat" ng-model="val.type" maxlength="40" ng-maxlength="40" required ng-if="contenteditable" ng-blur="check_section_title()">
</div>
</form>
</body>
</html>

angularjs save html from textarea

this is my html:
<div ng-if="!item.edit>
<div class='door-description' ng-bind-html="item.Description"></div>
<div class='door-softvalues' ng-bind-html="item.SoftValues" ng-if="item.IsConfiguration"></div>
</div>
<div ng-if="item.edit">
<textarea elastic class='door-description' ng-bind-html="item.Description" ng-model="item.Description"></textarea>
<textarea elastic class='door-softvalues' ng-bind-html="item.SoftValues" ng-if="item.IsConfiguration" ng-model="item.SoftValues"></textarea>
</div>
So the linebreak looks good when im in edit mode and do the edit to the textarea but when i save the text and retrieve it again it looses the linebreaks.
Here is what it looks like when editing:
And here is what it looks like when not editing:
I can still toggle between edit and not editing and i will get the same result.
What do i have to do to make the linebreaks appear when not editing?
Can you try using pre tag:
<pre class='door-description' ng-bind-html="item.Description"></pre>
Just apply this style to your element:
white-space: pre;
Can you please use like this ,
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-sanitize.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<textarea elastic class='door-description' ng-bind-html="myText " ng-model="myText "></textarea>
</div>
<script>
var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
$scope.myText = "My name is: <div><h1>John Doe</h1></div>";
});
</script>
may be this will work .
It will give object like ,
My name is: <div><h1>John Doe</h1></div>

AngularJS in line edit

I have a small piece of code, which I would like to extend with in line editting possibilities:
HTML:
<h1>Schedule <label ng-click="modifyText(index)">{{th.schedules[index].label}} </label>
</h1>
JS:
$scope.modifyText = function(index) {
this.th.schedules[index].label = 'modifiedtext';
};
Hence I would like to be able to click {{th.schedules[index].label}}, modify it inline to the string: "modifiedtext", and save it.
How can I do that?
Thank you.
In order to edit a label inline, you would probably have to use the contentEditable attribute since it isn't directly an editable element. If you give it an ng-model changing that data could be easier but you will still have to make a UI for actually editing it.
Instead I made an example using a text input and some simple styling to make it seem as though it isn't a text input when it isn't focused
http://jsfiddle.net/yrakrj48/
//-- HTML
<body ng-app="TestApp">
<div ng-controller="TestController">
<input ng-class="editing ? 'hasBorder' : 'noBorder'" type="text" ng-model="myLabel" ng-focus="editing = true" />
<button ng-if="editing" ng-click="saveEdit()">done</button>
</div>
</body>
//-- JS
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope) {
$scope.myLabel = 'this is a label';
$scope.saveEdit = function() {
$scope.editing = false;
};
});
//-- CSS
.hasBorder {
border:1px solid #666;
}
.noBorder {
border:none;
}
You should look into directives because creating one would be easy and I am sure one already exists somewhere out on github
I think you use. contenteditable=true
<div contenteditable=true>
I am Editable
</div>

AngularJS ng-repeat get the index of the button clicked and used in jquery

I got some code here, what I want to do is when I click the button I change the checkbox value and at the same time change the color of the button.
(check=red,uncheck=black for example)
I think it is easier to do it with jquery. My idea is to get the index of which button is clicked. change the value of the checkbox with the same index and the button color.
But I just cannot figure out how to select the button and the checkbox.
<div id="allcolrepeat">
<div style="width:200px; float:left; margin:5px;" ng-repeat="col in allColumns">
<input class="colCheckbox" type="checkbox" ng-change="changeCheck(col.displayName)" ng-model="checkvalue[col.displayName]">
<button>{{col.displayName}}</button>
</div>
</div>
Any help will be appreciated. Thanks.
You can use ngClass directive
The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.
Code
<button ng-class="checkvalue[col.displayName] == true ? 'red' : 'black'">{{col.displayName}}</button>
Another way of using it is
ng-class="{'red': checkvalue[col.displayName], 'black': !checkvalue[col.displayName]}">
Note: Declare red and black css class
If I understood well here is a simple JSFiddle
You can do it with many ways, you can use ngClass or ngStyle (second one in the example) to change CSS styling, then you need only to assign the scope variable to the ng-model to change the checkbox value.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div id="allcolrepeat">
<div style="width:200px; float:left; margin:5px;" ng-repeat="col in allColumns">
<input class="colCheckbox" type="checkbox" ng-model="col.displayName">
<button ng-style="{'background-color': color}" ng-click="col.displayName = 'CHANGED'; color = 'red'">{{col.displayName}}</button>
</div>
</div>
</div>
JS:
angular.module('myApp', [])
.controller('myCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.allColumns = [{displayName: 'hello'}, {displayName: 'world'}];
$scope.color = 'transparent';
}]);
Here I'm using ng-style to change the button color :
ng-style="{background : status[$index] ? 'red' : 'blue'}"
But you can also use :
ng-class="status[$index] === true ? 'red' : 'blue'"
function Main($scope) {
$scope.allColumns = [{displayName : "1"},{displayName : "2"},{displayName : "3"},{displayName : "4"},{displayName : "5"},{displayName : "6"},{displayName : "7"}]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="Main" id="allcolrepeat">
<div style="width:200px; float:left; margin:5px;" ng-repeat="col in allColumns track by $index">
<label>{{col.displayName}}</label>
<input ng-model="status[$index]" type="checkbox">
<button ng-style="{background : status[$index] ? 'red' : 'blue'}" ng-click="status[$index] = !status[$index]">OK</button>
</div>
</div>
As was mentioned in other answers it is better to use ng-style or ng-class for styling purposes.
But question was made and peoples from google-search will come to see how to get index with jQuery... So inside ng-repeat you can use '$index' (ngRepeat documentation) variable so you can use it as data attribute or whatever you want. In your particular case you can make
<div ng-repeat="item in items">
<button data-index={{$index}}>{{item}}</button>
</div>
And with jQuery make $('button').on('click', function() { $(this}.data('index') });

Assign dynamic controller in ng-repeat

I am new to Angularjs. I've tried a example in here.
file index.html:
<div ng-repeat="data in ctl.dataList">
<div class="col-md-6">
<textarea type="text" ng-mouseover="ctl.mouseOverFunc()" ng-mouseleave="ctl.mouseLeaveFunc()">{{data.value}}</textarea>
<button ng-show="ctl.showCloseBtn">X</button>
</div>
</div>
file app.js:
app.controller('FocusController', function() {
this.showCloseBtn = false;
this.dataList = [{
value: "one"
}, {
value: "two"
}];
this.mouseOverFunc = function() {
this.showCloseBtn = true;
};
this.mouseLeaveFunc = function() {
this.showCloseBtn = false;
};
});
I want to show close button when mouse overed every textarea like facebook chat in this picture. But my issues is when mouse over one of textarea then all X button was showed.
How do i assign dynamic controller to every textarea or how to do like facebook chat ?
Thanks for your help
You can do with CSS as well as AngularJS. I suggest you to do with CSS which is Simple. And Do your ng-click on the button.
This Plunker Demo is using with CSS and added ng-click there. Please check the styles and classes added.
Styles
<style>
.field:hover .btn-close {
display:block;
}
.btn-close {
display:none;
}
</style>
HTML
<div ng-repeat="data in ctl.dataList">
<div class="col-md-7 field">
<textarea></textarea>
<button ng-click="doSomething()" class="btn-close">X</button>
</div>
</div>
This Plunker Demo is with AngilarJS as explained in the other answer by New Dev.
<div ng-repeat="data in ctl.dataList">
<div ng-mouseover="data.showX = true"
ng-mouseleave="data.showX = false">
<textarea></textarea>
<button ng-click="doSomething()" ng-show="data.showX">X</button>
</div>
Typically, it would be best to create a directive for this functionality and encapsulate all the logic of clicking the "x" button, but for simplicity you could also leverage the child scope created by ng-repeat, and do the following:
<div ng-repeat="data in ctl.dataList">
<div ng-mouseover="data.showX = true"
ng-mouseleave="data.showX = false">
<textarea type="text"></textarea>
<button ng-show="data.showX" ng-click="ctl.close(data)">X</button>
</div>
</div>
ng-repeat="item in items" creates a child scope for each item, so you can set values on the child scope.
Here's your modified plunker
EDIT:
As suggested in the comments, if you have nothing more complex than showing or hiding the button, definitely CSS approach is the simplest way to go. Use the above example then as an illustration for how scopes work.

Categories

Resources