Regarding angular js directives usage - angularjs

i am learning angular so when reading article then some time getting stuck to understand the output. here i confusion of render html output.
code taken from http://www.w3schools.com/angular/tryit.asp?filename=try_ng_directive
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" w3-test-directive></div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>
</body>
</html>
when the above code runs then output as follows
<div w3-test-directive="" ng-app="myApp" class="ng-scope">I was made in a directive constructor!</div>
my question is why the directive's template text gets added within start and end div tag ?`
why this attribute is blank w3-test-directive="" in div ?
this text I was made in a directive constructor! could have added in the attribute of w3-test-directive so the html output may look like
<div w3-test-directive="I was made in a directive constructor!" ng-app="myApp" class="ng-scope"></div>
please help me to understand why the directive's template text gets added within start and end div tag ?` thanks

How you use directives depends on the 'restrict' property.
If you add restrict: 'E', then you can use it as a element, ex:
<foo></foo>
If you do restrict: 'A', now its:
<div foo></div>
More info:
http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-i-the-fundamentals
Example:
angular.module('moduleName')
.directive('foo', function () {
return {
restrict: 'EA', //E = element, A = attribute, C = class, M = comment
template: 'Foo'
}
});

The template or the content from templateURL is always inserted between the enclosing tags on which the directive is used. Hence the template text added inside the div tags. This happen because untill it gets to html, it will never be displayed.
w3-test-directive="" : this is because of the fact that this as a attribute has no value. Since it not a known attribute in html, it has no default value, so it will be parsed like this.
I have added an example where i am using the same directive as an element tag instead of using it as a attribute
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">
<w3-test-directive></w3-test-directive>
</div>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>
</body>
</html>

A directive renders its template within the element upon which it is declared. The w3-test-directive directive is being declared (as an attribute) on your div element:
<div ng-app="myApp" w3-test-directive></div>
It will therefore render your template within that element's opening and closing tags, and won't (by default) affect anything higher in the DOM tree.
Also, about valueless attributes - they don't need values. For example, the disabled or async attributes do not normally have values. That a particular attribute is merely present is enough, in many cases. In Angular, the presence of a directive, declared as an attribute, is often all that is needed. If you provide values, they will be interpreted as references to model data (handled by the your scope declaration within the directive definition).

why this attribute is blank w3-test-directive="" in div ?
blank space is because it show that attributes as Html5 compliance no html5 errors or warnings. same as if we write disable or readonly property.
ng-directives have menu types to declare for example :
<div ng-app="myApp" w3-test-directive></div>
above example of 'A' means Attribute it can be write as follows:
following example with 'E' Element
<div ng-app="myApp">
<w3-test-directive></w3-test-directive>
</div>
following example with 'C' Class
<div ng-app="myApp">
<span class='w3-test-directive'></span>
</div>
for more info please refer following link:
[angular directives][1]
[1]: https://docs.angularjs.org/guide/directive

Related

Unable to use custom directive when ng-model is used

While trying to use custom directive with an output linked to text field im getting below issue
[$compile:tplrt] Template for directive 'myDir' must have exactly one
root element.
http://errors.angularjs.org/1.5.0/$compile/tplrt?p0=myDir&p1= can some
one show some light here
Code
<!DOCTYPE html>
<html ng-app="myapp1">
<head>
<title> ANGULAR</title>
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('myapp1', []).directive('myDir', function() {
return {
restrict: 'E',
replace: true,
template: '<input type="text" ng-model="title"> {{title}}'
};
});
</script>
</head>
<body>
<div>
<my-dir>sadas</my-dir>
</div>
</body>
</html>
Error message is clear I guess your template should look like this:
<div><input type="text" ng-model="title"> {{title}}</div>
instead of just:
<input type="text" ng-model="title"> {{title}}
You have set your directive replace:true which is deprecated by the way. Since you are replacing element your template should compile to a single root.
If you remove replace attribute, you can use the template you have now. Demo.
directive('myDir', function() {
return {
restrict: 'E',
// don't use deprecated option replace: true
template: '<input type="text" ng-model="title"> {{title}}'
};
});
When a directive is declared with template (or templateUrl) and replace mode on, the template must have exactly one root element. That is, the text of the template property or the content referenced by the templateUrl must be contained within a single html element.
For example,
<p>blah <em>blah</em> blah</p> instead of simply blah <em>blah</em> blah
Otherwise, the replacement operation would result in a single element (the directive) being replaced with multiple elements or nodes, which is unsupported and not commonly needed in practice.
https://docs.angularjs.org/error/$compile/tplrt

Angular Directives and Routing

I have an Angular app consisting of an HTML page, a view being routed to that page, and a template for a directive that I want to add to the view being routed.
The index.html page displays the view using ngRoute fine. I am trying to use angular charts withing the view that is being routed, but I can't get the chart to show up. The code for the html page being routed is:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
---Some Code----
<div create-chart></div>
</body>
</html>
The "create-chart" element refers to the directive which creates a chart in a separate html template.
The code for constructing the directive is:
var app = angular.module('penny', ['ngRoute', 'pennyControllers']);
app.config(['$routeProvider', ...
var chart = angular.module('chart', ['chart.js']);
app.directive('createChart', function () {
return {
restrict: 'E',
templateUrl: '../chart/chart.html'
};
});
Does anyone know why the chart won't display?
"A" is for attribute, "E" is for element. Since you are calling the directive from an attribute so use the following:
restrict: 'A'
In your code you have put restrict: 'E'
It's maybe not the reason but 'E' is for element.
With this you should used
<create-chart></create-chart>
First of all try restrict: 'A' to used <div create-chart></div>

$compile service in angular returns an array

I am trying to compile a static DOM against scope using the following code
(function(angular) {
var app = angular.module("directiveModule1",[]);
app.controller('testController', ['$scope', function($scope){
$scope.UserName = "afh";
}]);
app.directive("linkFuncDirective",['$compile', function($compile) {
return {
link: function(scope, element, attrs,controller) {
var markUp = "<input type = 'text' ng-model ='UserName'/>{{UserName}}</br>";
var linkFunc = $compile(markUp);
var content = linkFunc(scope);
angular.element(element).html(content);
//angular.element(element).html($compile(markUp)(scope));
}
};
}]);
})(window.angular);
and my html is below
<html>
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.5" src="https://code.angularjs.org/1.4.0-beta.5/angular.js"></script>
<script src="directiveWithLinkFunction.js"></script>
</head>
<body ng-App="directiveModule1">
<div ng-controller="testController">
<div link-func-directive></div>
</div>
</body>
</html>
and I get the following o/p
[[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]]
Trying to understand what was written wrong in code, any help is highly appreciated
The reason behind html is having [[object HTMLInputElement], [object HTMLSpanElement], [object HTMLBRElement]] on view is, You have compiled one line of html using $compile service which returns below as compiled DOM
<input type="text" ng-model="UserName">
<span class="ng-binding ng-scope"></span>
<br class="ng-scope">
So basically it has 3 elements, 1st one is input element, 2nd is span & 3rd is br break tag. So when you try to add it as HTML to page using .html method, jQLite internally takes that object and apply .toString() method to making sure it should accept the string. That's the reason why you are getting [Object...] in the output.
Basically your problem is you are assigning compiled angular DOM html content to the directive element html, which wouldn't make sense.
It should be .append function instead of .html as angular compiled DOM will get injected will have binding enabled.
element.append(content); //would append the DOM with angular compiled DOM.
Why do you want to compile that in the first place ? You can use a simple template for that.
Your code is a little bit mess. Try to clean up first.
give a restrict property to your directive
if you don't have a required field then you don't need a controller parameter
Why don't you just simple use a template for your directive

Angularjs | how to get an attribute value from element in which controller is defined

I'm still fighting with simple things in Angular. I have jQuery and Backbonejs background, so please do not yell on me. I try hard to understand differences
I have HTML in which from rails is given ID of project as data-project-id:
<div data-ng-controller="ProjectCtrl as ctrl" data-project-id="1" id="project_configuration">
Is there any chance to get access to this attribute? I need it to my API calls...
To access an elements attributes from a controller, inject $attrs into your controller function:
HTML
<div test="hello world" ng-controller="ctrl">
</div>
Script
app.controller('ctrl', function($attrs) {
alert($attrs.test); // alerts 'hello world'
});
In your example, if you want to get data-project-id:
$attrs.projectId
Or if you want to get id:
$attrs.id
Demo:
var app = angular.module('app',[]);
app.controller('ctrl', function($attrs) {
alert($attrs.test);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl" test="hello world">
</div>
In Angular world you should use directives to manipulate with DOM elements. Here a nice explanation how to get attribute value from custom directive (How to get evaluated attributes inside a custom directive).
But if you still want to get it's value from controller you are able to use jQuery as well $('#project_configuration').data('project-id')

Accessing controller name outside of ng-view

Is there a way to access the name of a controller when the controller is defined seperate from ng-view?
<div ng-controller="Ctrl1">
<!-- Some code -->
</div>
<div ng-view>
<!-- Configured with ngRoute -->
</div>
Within ng-view I'm able to use $route.current.controller to retrive the current controller name. If possible how would I achieve the same thing for "Ctrl1"?
Thanks a bunch!
Unlike the ng-view, it's possible that there are more than one ng-controller in the same page.
Therefore, it's impossible to have something like $route.current.controller to get the current controller.
But if your goal is to just print every controller name that get initialized via ng-controller, you could write a custom directive with the same name ngController.
app.directive('ngController', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
console.log(attrs.ngController);
}
};
});
This will output the value inside the ng-controller attribute whenever any ngController directive has been compiled.
Hope this helps.

Resources