how to make custom directive? - angularjs

I am new to angularjs ,building my first angular app now i want to display the data which i displayed right now in a table using a customized directive.
can anyone tell me how can i do this?
i just want to have a custom directive and all data should be displayed using that directive.
is customized directive should placed in a separate file?
please guide me how can i do it?
here is my controller:
'use strict';
app.controller('myAppCtrl', function ($scope, $http) {
$scope.names = []
$http.get('https://www.reddit.com/r/worldnews/new.json')
.success(function (response) {
$scope.names = response.data.children;
})
});
https://jsfiddle.net/rr6q0umb/4/

You should go through some resources online to study about angular directives .
https://docs.angularjs.org/guide/directive
http://www.tutorialspoint.com/angularjs/angularjs_custom_directives.htm
Simple directive approach for beginners
//Controller
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
//Directive
app.directive('simpleDemo',function(){
var newtemplate = function(){
var template = '<i class="glyphicon glyphicon-remove"><i>';
return template;
}
return {
restrict: 'E',
template: newtemplate
}
})
//html
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<button><simple-demo></simple-demo></button>

It might help you!
<html>
<head>
<title>Angular JS Custom Directives</title>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> , Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.rollno = 2;
});
</script>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="StudentController">
<student name="Mahesh"></student><br/>
<student name="Piyush"></student>
</div>
</body>
</html>
Reference URLs:
https://www.airpair.com/angularjs/posts/creating-components-p3-angular2-directives
http://tutorials.jenkov.com/angularjs/custom-directives.html
http://www.sitepoint.com/practical-guide-angularjs-directives/

Related

How to get the URL for the file selected in File Explorer using AngularJS

I need to click on the Choose file and select the file from the file explorer, then I need to get the URL for the selected file and store it in variable.Can you please look in to the below code and guide me since i am new to AnularJS...Thanks in Advance.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body >
<div ng-app = "myApp" ng-controller="myControl">
<input type="file" file-model="myFile" ng-module = "file_name" ng-click = "file_name()"><br>
<h1>{{file_name()}}</h1>
</div>
<script>
var app= angular.module("myApp",[]);
app.controller("myControl",function($scope){
$scope.file_name = function(){
return $scope.file_name;
};
});
</script>
</body>
</html>
You can create url directive. Inside controller you should use $watch method to catch the moment, when file_name property will be assigned. At this example you can select picture file and it will be shown:
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope) {
$scope.$watch('file_url', function(newVal, oldVal) {
if (newVal != oldVal)
console.log(newVal);
}, true)
}])
.directive('url', function() {
return {
restrict: 'A',
scope: {
url: '='
},
link: function(scope, element) {
element.on('change', function(event) {
var reader = new FileReader();
reader.onloadend = function() {
scope.$apply(function() {
scope.url = reader.result;
});
}
var file = element[0].files[0];
if (file)
reader.readAsDataURL(file);
})
}
}
})
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
<div ng-app='app' ng-controller="ctrl">
<img src="{{file_url}}" height="150" alt="Image preview...">
<input type="file" url='file_url'>
</div>

How to call custom function in AngularJS Directive

I'm trying to call $scope function in AngularJS Directive in following way
JS
var app = angular.module('app', []);
app.controller('customDirEx', ['$scope', function ($scope) {
$scope.users = [
{
name: 'ABC',
rno: '100'
},
{
name: 'DEF',
rno: '200'
}
];
$scope.onChangeFoo = function() {
console.log('test');
}
$scope.dataChange = function() {
console.log('test abc', $scope);
$scope.onInitEle();
}
$scope.dataChange();
}]);
app.directive('studentInfo', function(){
var directive = {};
directive.scope = {
user: '=user',
onInitEle: '='
};
directive.restrict = 'EA';
directive.template = '<div>Name: {{user.name}}<br>R.NO: {{user.rno}}</div>';
return directive;
});
HTML
<body ng-app="app">
<div ng-controller="customDirEx">
<student-info ng-repeat="user in users" user="user" on-init-ele="onChangeFoo"></student-info>
</div>
</body>
$scope.onInitEle is not a function - this is the error I'm getting
The purpose of calling onClickEle instead of onChangeFoo here is too reuse the JS at multiple places so that I can call onChangeBar when required.
First you have to replace "onClickEle: '='" with "onClickEle: '&'"
The use of & means you are passing reference.
The second mistake is you didn't call it from your template. So, I have changed your template code as:
directive.template = '<div ng-click="onClickEle()"> Name: {{user.name}}<br>R.NO: {{user.rno}}</div>';
The third mistake is: you are calling $scope.onClickEle(); in controller, however onClickEle() not defined in controller, its under directive. So, controller unable to find the method.
The forth mistake is you are passing on-click-ele="onChangeFoo" in the direcive, the correct syntax will be:
on-click-ele="onChangeFoo()"
The working updated code given below:
var app = angular.module('app', []);
app.controller('customDirEx', ['$scope', function ($scope) {
$scope.users = [
{
name: 'ABC',
rno: '100'
},
{
name: 'DEF',
rno: '200'
}
];
$scope.onChangeFoo = function() {
console.log('test....');
}
$scope.dataChange = function() {
console.log('test abc', $scope);
//$scope.onClickEle();
}
$scope.dataChange();
}]);
app.directive('studentInfo', function(){
var directive = {};
directive.scope = {
user: '=user',
onClickEle: '&'
};
directive.restrict = 'EA';
directive.template = '<div ng-click="onClickEle()"> Name: {{user.name}}<br>R.NO: {{user.rno}}</div>';
return directive;
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="customDirEx">
<student-info ng-repeat="user in users" user="user" on-click-ele="onChangeFoo()"></student-info>
</div>
</body>
</html>
Somehow I can manage this by creating separate controller for directive but don't know the theory behind, it would be very helpful if someone explains clearly.
JS
var app = angular.module('app', []);
app.controller('customDirEx', ['$scope', function ($scope) {
$scope.users = [
{
name: 'ABC',
rno: '100'
},
{
name: 'DEF',
rno: '200'
}
];
$scope.onChangeFoo = function() {
console.log('test');
}
}]);
app.controller('StudentCtrl', ['$scope', function($scope){
$scope.onInitEle();
}]);
app.directive('studentInfo', function(){
var directive = {};
directive.scope = {
user: '=user',
onInitEle: '='
};
directive.restrict = 'EA';
directive.template = '<div>Name: {{user.name}}<br>R.NO: {{user.rno}}</div>';
directive.controller = 'StudentCtrl';
return directive;
});
HTML
<body ng-app="app">
<div ng-controller="customDirEx">
<student-info ng-repeat="user in users" user="user" on-init-ele="onChangeFoo"></student-info>
</div>
</body>
Working JSFiddle

How do I register a directive in a custom module

I have created a directive but the .directive code is never executed. I'm sure the problem is something obvious, but I can't see it:
Example on Plunkr
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="app">
<responsive-parent>xxx</responsive-parent>
</div>
<script>
angular.module("mrpmorris.responsive-parent", [])
.directive("responsive-parent", [
"$window", "$timeout",
function ($window, $timeout) {
console.log("**** THIS IS NEVER REACHED ****");
return new mrpmorris.responsiveParent.Directive($window, $timeout);
}
]);
var mrpmorris;
(function (mrpmorris) {
var responsiveParent;
(function (responsiveParent) {
var Directive = (function () {
function Directive($window, $timeout) {
var _this = this;
this.$window = $window;
this.$timeout = $timeout;
this.restrict = "E";
this.template = "<h1>It works</h1>";
this.replace = true;
}
return Directive;
}());
responsiveParent.Directive = Directive;
})(responsiveParent = mrpmorris.responsiveParent || (mrpmorris.responsiveParent = {}));
})(mrpmorris || (mrpmorris = {}));
angular.module("app", ["mrpmorris.responsive-parent"]);
</script>
</body>
</html>
The directive should be named responsiveParent, not responsive-parent.
It would still be used using responsive-parentin the view, though.
This is all explained in the documentation.

best way in remove directive by unique id in angularjs

i have simple directive that create a text, after click to add buttom.
and after click to each directive remove and destroy directive properly.
but i need delete all directive after selected.
for example i clicked to add button for 5 step and result same bellow
Directive content
Directive content
Directive content
Directive content
Directive content
i need click to item 2 then remove and destroy scope of item 3,4,5
another question is , can i delete directive by spsephic id ?
<body ng-app="app">
<div ng-controller="MainController">
<button ng-click="Stage()">{{stage}}</button>
<div class="my-directive-placeholder"></div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('MainController', function($scope, $compile, $element){
$scope.stage = 'Add';
var childScope;
$scope.Stage = function(){
childScope = $scope.$new();
var el = $compile( "<b my-directive></b>" )(childScope);
$('.my-directive-placeholder').append(el);
}
})
app.directive('myDirective', function($interval){
return {
template: 'Directive content<br>',
link: function(scope, element, attrs){
element.on('click', function () {
scope.$destroy();
element.remove();
});
scope.$on('$destroy', function(){
console.log('destroid');
});
}
}
});
</script>
https://jsfiddle.net/0vucwqrc/
Instead creating html on compile time, may be its better to have dedicated directive for this like, See if this fits your requirment
angular.module('MyApp', [])
angular.module('MyApp')
.controller("DirectivePageController",
function() {
var self = this;
self.fields = [{
Name: 'Directive1'
}];
self.newField = function() {
self.fields.push({
Name: ('Directive' + (self.fields.length + 1))
});
};
self.removeField = function(field) {
var index = self.fields.indexOf(field);
if (index >= 0) {
self.fields.splice(index, 1);
}
};
})
.controller("appDirectiveController", ['$scope', '$attrs',
function($scope, $attrs) {
var self = this;
var directiveScope = $scope.$parent;
self.options = directiveScope.$eval($attrs.model);
self.onOk = function() {
alert(JSON.stringify(self.options) + ' button clicked');
}
}
])
.directive('appDirective', function($compile) {
return {
transclude: true,
template: '<div ng-click="dirCtrl.onOk()" type="">{{type|uppercase}}</div>',
scope: {
index: '#',
type: '#'
},
restrict: 'E',
replace: true,
controller: 'appDirectiveController',
controllerAs: 'dirCtrl',
}
})
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<body>
<div ng-app="MyApp">
<div ng-controller="DirectivePageController as pageCtrl">
<span>Add Button</span>
<div ng-repeat="field in pageCtrl.fields track by $index">
<app-directive type="{{field.Name}}" model="field">
</app-directive>
Remove
</div>
</div>
</div>
</body>
</html>

ng-include with ng-src not working

I'm trying to compile a template which has data-ng-include and data-ng-src defined. I'm trying to set the src by calling getPartial(), which returns the path of the template. But the getPartial() is not getting called.
HTML:
<button ng-click="displayElements();">Display Elements</button>
<div id="container"></div>
JS:
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-src="getPartial()"></div>';
var linkFn = $compile(template)($scope);
//console.log(angular.element(document.getElementById("container")));
angular.element(document.getElementById("container")).append(linkFn);
}
$scope.getPartial = function() {
console.log("from partial");
return 'hello.html';
}
Plnkr : http://plnkr.co/edit/ig9TAXVpK4k1bQwi9PQo?p=preview
ng-include uses either its own value or value of src attribute to get the path (see documentation). You're trying to use ng-src, which is a directive in its own right. So you need to do either this:
<div data-ng-include="getPartial()"></div>
or this:
<div data-ng-include data-src="getPartial()"></div>
On a sidenote, watching a function call result hurts performance. You'd be better served by putting the resolved source path into a scope variable.
Here is the solution:-
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile) {
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var linkFn = $compile(template)($scope);
angular.element(document.getElementById("container")).append(linkFn);
};
$scope.getPartial = function() {
alert("from partial");
$scope.htmlToLoad = 'hello.html';
};
}]);
http://plnkr.co/edit/y3PgeBMVHytftI7NDSq4?p=preview
'<div data-ng-include data-ng-src="getPartial()"></div>';
replace your code with this
'<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile) {
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var linkFn = $compile(template)($scope);
//console.log(angular.element(document.getElementById("container")));
angular.element(document.getElementById("container")).append(linkFn);
}
$scope.getPartial = function() {
alert("sdfsdfsdf");
console.log("from partial");
return 'hello.html';
}
}]);

Resources