Hello everyone, I am going to share the code
sample for differentiate to link and controller.
Link
: The link is a function and use to attached handlers and also use for DOM elements
modification.
Controller
: The controller is use to share the $scope data within the scope and also provide
the ways of linking the DOM elements.
Table
of Contents
- HTML code sample for link vs. controller
- AngularJs code sample for link vs. controller
- Full (HTML+ AngularJs) code sample for link vs. controller
- Live demo link http://embed.plnkr.co/cbsRod/preview
<div ng-app="linkApp">
<div ng-controller="linkCtrl">
<link-directive></link-directive>
</div>
</div>
var app =
angular.module('linkApp',
[]);
//This is controller section.
app.controller('linkCtrl', ["$scope", function ($scope) {
$scope.count = 'One ';
}]);
//This is directive section.
app.directive('linkDirective', function () {
return {
restrict: 'E',
template: '<span>This
is {{count}}!</span>',
controller: function ($scope, $element)
{
$scope.count = $scope.count + ", Two";
},
link: function (scope, el, attr) {
scope.count = scope.count + ",
Three";
}
}
});
Full
(HTML+ AngularJs) code sample for link vs. controller.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>AngularJS directive
controller vs. link</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script>
var app =
angular.module('linkApp',
[]);
//This is controller section.
app.controller('linkCtrl', ["$scope", function ($scope) {
$scope.count = 'One ';
}]);
//This is directive section.
app.directive('linkDirective', function () {
return {
restrict: 'E',
template: '<span>This
is {{count}}!</span>',
controller: function ($scope, $element)
{
$scope.count = $scope.count
+ ", Two";
},
link: function (scope, el, attr) {
scope.count = scope.count +
", Three";
}
}
})
</script>
</head>
<body ng-app="linkApp">
<div ng-controller="linkCtrl">
<link-directive></link-directive>
</div>
</body>
</html>
For more detail you can go links