AngularJS Custom Directive

I am not going to write another blog to explain about the custom directives in Angular JS. The documentation of AngularJS is a perfect source for learning about them.In this post, lets just play around a custom directive.

I just want to display the name of a file browsed. So, here goes the simple controller and custom directive code,

main.js

var coreApp = angular.module("coreApp", []);

coreApp.directive('fileUpload', function()
{
	return {
	scope : false,
	link : function(scope, elem, attr)
	{
		elem.on('change', function(event)
		{
			var file = event.target.files[0];
			scope.$apply(function()
			{
				scope.data.name = file.name;
				scope.data.file=file;
			});

		});
	}
	}
});

coreApp.controller('myController', function($scope)
{
	$scope.data = {
		name : '',
		file:null
	};

});

And here is the simple html page,

test.html

<html>
	<head>
		<title>Angular JS Directive.</title>
		<script src="js/angular.min.js"></script>
		<script src="js/main.js"></script>
	</head>
	<body ng-app="coreApp" ng-controller="myController">
		<h2>AngularJS Sample Application</h2>
		<div>
			<input type="file" file-upload />
		</div>
		<div>
			<p>File Selected </p>
			{{data.name}}
		</div>
	</body>
</html>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s