How to manipulate DOM elements with Angular - angularjs

I just can't find a good source that explains to me how to manipulate DOM elements with angular:
How do I select specific elements on the page?
<span>This is a span txt1</span>
<span>This is a span txt2</span>
<span>This is a span txt3</span>
<span>This is a span txt4</span>
<p>This is a p txt 1</p>
<div class="aDiv">This is a div txt</div>
Exp: With jQuery, if we wanted to get the text from the clicked span, we could simple write:
$('span').click(function(){
var clickedSpanTxt = $(this).html();
console.log(clickedSpanTxt);
});
How do I do that in Angular?
I understand that using 'directives' is the right way to manipulate DOM and so I am trying:
var myApp = angular.module("myApp", []);
myApp.directive("drctv", function(){
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs){
var c = element('p');
c.addClass('box');
}
};
});
html:
<drctv>
<div class="txt">This is a div Txt</div>
<p>This is a p Txt</p>
<span>This is a span Txt </span>
</drctv>
How do I select only 'p' element here in 'drctv'?

Since element is a jQuery-lite element (or a jQuery element if you've included the jQuery library in your app), you can use the find method to get all the paragraphs inside : element.find('p')

To Answer your first question, in Angular you can hook into click events with the build in directive ng-click. So each of your span elements would have an ng-click attribute that calls your click function:
<span ng-click="myHandler()">This is a span txt1</span>
<span ng-click="myHandler()">This is a span txt2</span>
<span ng-click="myHandler()">This is a span txt3</span>
<span ng-click="myHandler()">This is a span txt4</span>
However, that's not very nice, as there is a lot of repetition, so you'd probably move on to another Angular directive, ng-repeat to handle repeating your span elements. Now your html looks like this:
<span ng-repeat="elem in myCollection" ng-click="myHandler($index)">This is a span txt{{$index+1}}</span>
For the second part of your question, I could probably offer an 'Angular' way of doing things if we knew what it was you wanted to do with the 'p' element - otherwise you can still perform jQuery selections using jQuery lite that Angular provides (See Jamie Dixon's answer).
If you use Angular in the way it was intended to be used, you will likely find you have no need to use jQuery directly!

You should avoid DOM manipulation in the first place. AngularJS is an MVC framework. You get data from the model, not from the view. Your example would look like this in AngularJS:
controller:
// this, in reality, typically come from the backend
$scope.spans = [
{
text: 'this is a span'
},
{
text: 'this is a span'
},
{
text: 'this is a span'
}
];
$scope.clickSpan = function(span) {
console.log(span.text);
}
view:
<span ng=repeat="span in spans" ng-click="clickSpan(span)">{{ span.text }}</span>

ng-click is the simpler solution for that, as long as I do not really understand what you want to do I will only try to explain how to perform the same thing as the one you have shown with jquery.
So, to display the content of the item which as been clicked, you can use ng-click directive and ask for the event object through the $event parameter, see https://docs.angularjs.org/api/ng/directive/ngClick
so here is the html:
<div ng-controller="foo">
<span ng-click="display($event)" >This is a span txt1</span>
<span ng-click="display($event)" >This is a span txt2</span>
<span ng-click="display($event)" >This is a span txt3</span>
<span ng-click="display($event)" >This is a span txt4</span>
<p>This is a p txt 1</p>
<div class="aDiv">This is a div txt</div>
</div>
and here is the javascript
var myApp = angular.module("myApp", []);
myApp.controller(['$scope', function($scope) {
$scope.display = function (event) {
console.log(event.srcElement.innerHtml);
//if you prefer having the angular wrapping around the element
var elt = angular.element(event.srcElement);
console.log(elt.html());
}
}]);
If you want to dig further in angular here is a simplification of what ng-click do
.directive('myNgClick', ['$parse', function ($parse) {
return {
link: function (scope, elt, attr) {
/*
Gets the function you have passed to ng-click directive, for us it is
display
Parse returns a function which has a context and extra params which
overrides the context
*/
var fn = $parse(attr['myNgClick']);
/*
here you bind on click event you can look at the documentation
https://docs.angularjs.org/api/ng/function/angular.element
*/
elt.on('click', function (event) {
//callback is here for the explanation
var callback = function () {
/*
Here fn will do the following, it will call the display function
and fill the arguments with the elements found in the scope (if
possible), the second argument will override the $event attribute in
the scope and provide the event element of the click
*/
fn(scope, {$event: event});
}
//$apply force angular to run a digest cycle in order to propagate the
//changes
scope.$apply(callback);
});
}
}
}]);
plunkr here: http://plnkr.co/edit/MI3qRtEkGSW7l6EsvZQV?p=preview
if you want to test things

Related

Angular JS directives with isolate scopes and internal controllers

I haven't touched angular js in a while and back when I did write, we used a flavour with typescript which was pretty straightforward with me. Now I want to write vanilla angular js and I feel I am a bit confused.
Problem:
I have a directive with a few variables in its isolate scope and I basically want to bind to this directive that is spawned inside a for each <ul> to a click event. I tried with directly binding a function on ng-click and with link element e.t.c. bind on click, but it seems I am doing something wrong since with the first way nothing happens, with the second way the two-way bound variable is undefined.
Here it goes:
https://plnkr.co/edit/OOBMs8pYONLjUE9lQXla?p=preview
activity-header.html
<div>
<h4>
Activity Name: {{activity.activity_name}}
</h4>
<h6>
Activity Start Date: {{activity.activity_start_date}}
</h6>
<h6>
Activity End Date: {{activity.activity_end_date}}
</h6>
<h6>
Participants: {{activity.participants}}
</h6>
</div>
activity-header.js
var app = angular.module('mainApp');
/*
app.controller('activityHeaderCtrl', ['$scope', function($scope) {
$scope.activity='';
$scope.msg='';
$scope.check = function() {
alert($scope.msg);
};
}]);
*/
app.directive('activityHeader', function() {
return {
restrict: 'AE',
templateUrl: 'activity-header.html',
controller: ['$scope', Controller],
scope: {
activity:'=',
msg:'='
},
link: function($scope, $element, attrs) {
$element.bind('click', function($scope) {
alert($scope.msg);
})}
};
function Controller($scope) {
$scope.check = function() {
alert($scope.msg);
};
}
});
index.html
<html ng-app="mainApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script-main.js"></script>
<script src="activity-header.js"></script>
<body>
<div ng-controller="ctrl">
<h1>
Major Bla bla System
</h1>
<ul>
<li ng-repeat="x in events">
<div activity-header activity="x" msg="greetingsfriend" ng-click="check()"></div>
</li>
</ul>
<h6>
Beta v.0.2
</h6>
</div>
</body>
</html>
script-main.js
var app = angular.module('mainApp', []);
app.controller('ctrl', function ($scope) {
//$scope.events = ["Elections", "Protest", "Martial Law", "X-mas Celebration"];
$scope.events = [
{"activity_name": "Elections", "activity_start_date": "31/12/2014", "activity_end_date": "31/12/2015", "participants": "1453"},
{"activity_name": "Martial Law", "activity_start_date": "31/12/2014", "activity_end_date": "31/12/2015", "participants": "1821"},
{"activity_name": "Protest", "activity_start_date": "31/12/2014", "activity_end_date": "31/12/2015", "participants": "1940"},
{"activity_name": "X-mas Celebration", "activity_start_date": "31/12/2014", "activity_end_date": "31/12/2015", "participants": "2009"}
];
$scope.salute = function () {
alert('hello there');
};
});
(By the way, I'm using Mozilla Firefox, otherwise I'd have to host it e.g. on node.js for the same origin policy, don't know how to turn it off in chrome/ internet explorer).
depends on what you want to obtain.
For example, if you want to bind a function of your directive on click you don't need the link function. You can simply bind a click on your outer div with ng-click. See this example: http://jsbin.com/sanova/edit?html,js,output
But if you want to call a function on your parent controller you need to pass a reference to that function with a property on your directive. See this example: http://jsbin.com/peqasu/edit?html,js,output
As you can see i've put in both example a ng-click directive on the outer div in your directive template. On click the check function on the directive controller is invoked. In the first example simply alert the message, in the second one calls the greetFunction passed as a property of your directive.
Any idea on how to handle the click?
Your problem is that you are using $scope as the name for the first argument in the click handler function. That name is overriding the $scope argument from the linking function.
//BAD
link: function($scope, $element, attrs) {
$element.bind('click', function($scope) {
alert($scope.msg);
})}
Fix your code like this:
//GOOD
link: function(scope, element, attrs) {
element.on('click', function clickHandler(event) {
console.log(scope.msg);
});
}
AngularJS jqLite invokes the click handler with a JQuery Event Object as the first argument not $scope.
Is this the correct way to handle events on directives?
Why doesn't the ng-click event ever work to call the function I have in my directive's controller?
The ng-click directive binds to functions in the parent scope.
To bind click events to functions on the directive's scope, use element.on(). It's how ng-click gets the event from the browser. Look at the source code.
First of all you need to know the difference between smart and dumb components (directives).
Here you can read a very good article explain the difference from smart and dumb components written by Dan Abramov, the creator of Redux: https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0
When you understand this difference you can try to write more dumb components and less smart one. This means that you need to keep all the logic on your parents components and pass it down to your dumb components.
In previous examples we do that only in the second one. In fact, in that example we keep the logic (our check function) in our parent component and only pass a reference to it. In this way the activity-header component have no idea of what to do when a click is done. It only know that it must call a function, what this function does is not its problem.
This is a good approach to have in a complex application, so you can reuse your components in different ways simply changing the reference function.

how to make custom directive in angular?

I am trying to make custom directive in angular .I try to add input field in my view when I click on button .In other words I am trying to make one custom directive in which when user press the button it add one input field in the browser .I think it is too easy if I am not use custom directive Mean If I use only controller then I take one array and push item in array when user click on button and button click is present on controller.
But when need to make custom directive where I will write my button click event in controller or directive
here is my code
http://play.ionic.io/app/23ec466dac1d
angular.module('app', ['ionic']).controller('appcontrl',function($scope){
$scope.data=[]
}).directive('inputbutton',function(){
return {
restrict :'E',
scope:{
data:'='
},
template:'<button>Add input</button> <div ng-repeat="d in data"><input type="text"></div>',
link:function(s,e,a){
e.bind('click',function(){
s.data.push({})
})
}
}
})
I just need to add input field when user click on button using custom directive ..could you please tell me where i am doing wrong ?
can we make button template and click event inside the directive
The reason it doesn't work is because your registering your click handler with jQuery. So when the click handler fires it is out of the scope of angular so angular does not know it needs to update its bindings.
So you have two options, the first is to tell angular in the click handler, 'yo buddy, update your bindings'. this is done using $scope.$apply
$apply docs: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply
e.bind('click',function(){
s.$apply(function() {
s.data.push({});
});
});
However angular already has built in directive for handling things like mouse clicks you can just use that and let angular do the work for you. This would be the better option.
so first in your view register a click handler on your button
<button ng-click="add()">Add input</button> <div ng-repeat="d in data"><input type="text"></div>
Then in your link simply add the add() method of your scope
s.add = function () {
s.data.push({});
}
Heres a working fiddle showing both examples. http://jsfiddle.net/3dgdrvkq/
EDIT: Also noticed a slight bug in your initial click handler. You registering a click but not specifying the button to apply it to. So if you clicked anywhere in the directive, not just the button, the handler would fire. You should be more specific when registering events manually, using ids, class names attributes etc.
The e or element property of the link function is a jqlite or full jQuery object of the entire directive. If you have jQuery included before angular it will be a full jQuery object. If not it will a jqlite object. A thinned out version of jQuery.
Here is a basic example for your logic .
var TestApp = angular.module('App', []);
// controller
TestApp.controller('mainCtrl', function mainCtrl($scope) {
$scope.data = [];
$scope.addDataItem = function () {
$scope.data.push({
someFilield: 'some value'
});
console.log('pushing value ... ');
}
});
// view
<div ng-app="App" class="container" ng-controller="mainCtrl">
<button type="button" ng-click="addDataItem()">Add an input</button>
<div ng-repeat="d in data track by $index">
<custom-directive model="d"></custom-directive>
</div>
</div>
// directive
TestApp.directive('customDirective', function customDirective() {
return {
restrict: 'E',
scope: {
model: '='
},
template: 'item -> <input type = "text" />',
link: function (scope, elem, attrs) {
console.log('scope.model', scope.model);
},
controller: function ($scope) {
// do staff here
}
}
});

Adding class to element using Angular JS

I know how to add a class on click of a button in 'jQuery'
$('#button1').click(function(){
$('#div1').addClass('alpha');
});
I want to achieve same thing by angular js. I have a controller - myController1. Can someone help me do it eazily?
AngularJS has some methods called JQlite so we can use it. see link
Select the element in DOM is
angular.element( document.querySelector( '#div1' ) );
add the class like .addClass('alpha');
So finally
var myEl = angular.element( document.querySelector( '#div1' ) );
myEl.addClass('alpha');
You can use ng-class to add conditional classes.
HTML
<button id="button1" ng-click="alpha = true" ng-class="{alpha: alpha}">Button</button>
In your controller (to make sure the class is not shown by default)
$scope.alpha = false;
Now, when you click the button, the $scope.alpha variable is updated and ng-class will add the 'alpha' class to your button.
Use the MV* Pattern
Based on the example you attached,
It's better in angular to use the following tools:
ng-click - evaluates the expression when the element is clicked (Read More)
ng-class - place a class based on the a given boolean expression (Read More)
for example:
<button ng-click="enabled=true">Click Me!</button>
<div ng-class="{'alpha':enabled}">
...
</div>
This gives you an easy way to decouple your implementation.
e.g. you don't have any dependency between the div and the button.
Read this to learn about the MV* Pattern
Try this..
If jQuery is available, angular.element is an alias for the jQuery function.
var app = angular.module('myApp',[]);
app.controller('Ctrl', function($scope) {
$scope.click=function(){
angular.element('#div1').addClass("alpha");
};
});
<div id='div1'>Text</div>
<button ng-click="click()">action</button>
Ref:https://docs.angularjs.org/api/ng/function/angular.element
First thing, you should not do any DOM manipulation in controller function.
Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.
AngularJS Docs : Creating a Directive that Manipulates the DOM
app.directive('buttonDirective', function($timeout) {
return {
scope: {
change: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
// triggering callback
scope.change();
});
});
}
};
});
change callback can be used as listener for click event.
querySelector is not from Angular but it's in document and it's in all DOM elements (expensive). You can use ng-class or inside directive add addClass on the element:
myApp.directive('yourDirective', [function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// Remove class
elem.addClass("my-class");
}
}
}
For Angular 7 users:
Here I show you that you can activate or deactivate a simple class attribute named "blurred" with just a boolean. Therefore u need to use [ngClass].
TS class
blurredStatus = true
HTML
<div class="inner-wrapper" [ngClass]="{'blurred':blurredStatus}"></div>
In HTML
To add the class named alpha, assign any variable like showAlpha to false first and then set it to true on click.
<div data-ng-class="{'alpha' : showAlpha}"> </div>
<button ng-click="addClass()"> </button>
In JS file
$scope.showAlpha = false;
$scope.addClass = function(){
$scope.showAlpha = true;
}
try this code
<script>
angular.element(document.querySelectorAll("#div1")).addClass("alpha");
</script>
click the link and understand more
Note: Keep in mind that angular.element() function will not find directly select any documnet location using this perameters
angular.element(document).find(...) or $document.find(), or use the standard DOM APIs, e.g. document.querySelectorAll()

Bind and parse HTML content

I am using AngularJS v1.2.1.
The improved ng-bind-html directive allows me to trust unsafe Html into my view.
Example
HTML:
<div ng-repeat="example in examples" ng-bind-html="example.content()"></div>
JS:
function controller($scope, $sce)
{
function ex()
{
this.click = function ()
{
alert("clicked");
}
this.content() = function ()
{
//if
return $sce.trustAsHtml('<button ng-click="click()">some text</button>');
// no problem, but click is not called
//when
return $sce.parseAsHtml('<button ng-click="click()">some text</button>');
//throw an error
}
}
$scope.examples = [new ex(), new ex()];
}
My question is, how to bind HTML content that may contain Angular expressions or directives ??
If you need dynamic templates per element, as your question suggests, one solution would be to use $compile within a directive to parse the HTML within the context of the local scope. A simple version of this is shown in this Plunk.
An example directive:
app.directive('customContent', function($compile) {
return function(scope, el, attrs) {
el.replaceWith($compile(scope.example.content)(scope));
}
});
The corresponding HTML:
<div ng-repeat="example in examples">
<div custom-content></div>
</div>
Notice that, in the Plunk controller, I've pulled out the click function into the scope for simplicity, since in the template HTML you are calling click() in the context of the scope, not on the example object. There are a couple ways you could use a different click function for each example, if that's what you'd like to do. This egghead.io screencast has a good example of passing an expression into a directive explicitly; in your case, it could be a click function or the whole example object, depending on what you need.

Ng-controller on same element as ng-repeat - no two-way-data-binding

I can't get two-way-data-binding to work in an Angular js ng-repeat.
I have an ng-controller specified on the same element that has the ng-repeat specified -
I just learnt that by doing this, I can get a hold of each item that is being iterated over by ng-repeat. Here is the HTML:
<div ng-controller="OtherController">
<div id="hoverMe" ng-controller="ItemController" ng-mouseenter="addCaption()"
ng-mouseleave="saveCaption()" ng-repeat="image in images">
<div class="imgMarker" style="{{image.css}}">
<div ng-show="image.captionExists" class="carousel-caption">
<p class="lead" contenteditable="true">{{image.caption}}</p>
</div>
</div>
</div>
</div>
And here is the ItemController:
function ItemController($scope){
$scope.addCaption = function(){
if($scope.image.captionExists === false){
$scope.image.captionExists = true;
}
}
$scope.saveCaption = function(){
console.log($scope.image.caption);
}
}
And the OtherController:
function OtherController($scope){
$scope.images = ..
}
When I hover the mouse over the #hoverMe-div - the caption-div is added correctly. But when I input some text in the paragraph and then move the mouse away from the #hoveMe-div, the $scope.image-variables caption value is not updated in the saveCaption-method. I understand I'm missing something. But what is it?
You don't need a ng-controller specified on the same element that has the ng-repeat to be able to get each item.
You can get the item like this:
<div ng-repeat="image in images" ng-mouseenter="addCaption(image)" ng-mouseleave="saveCaption(image)" class="image">
And in your controller code:
$scope.addCaption = function (image) {
if(!image.captionExists){
image.captionExists = true;
}
};
To get contenteditable to work you need to use ng-model and a directive that updates the model correctly.
Here is a simple example based on the documentation:
app.directive('contenteditable', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, controller) {
element.on('blur', function() {
scope.$apply(function() {
controller.$setViewValue(element.html());
});
});
controller.$render = function(value) {
element.html(value);
};
}
};
});
Note that the directive probably needs more logic to be able to handle for example line breaks.
Here is a working Plunker: http://plnkr.co/edit/0L3NKS?p=preview
I assume you are editing the content in p contenteditable and are expecting that the model image.caption is update. To make it work you need to setup 2 way binding.
2 way binding is available for element that support ng-model or else data needs to be synced manually. Check the ngModelController documentation and the sample available there. It should serve your purpose.

Resources