To associate a controller with a directive, you can use the Directive Definition Object's controller property. Either specifying the controller as a function or specifying the name of the controller.
Angular App
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', '$attrs', function($scope, $attrs) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
//Here are the attrs values
console.log($attrs.stars);
console.log($attrs.info);
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
starts: '=stars',
info: '=info'
},
//Associate a controller
controller: 'Controller',
template: "Name: {{customerInfo.name}} Address: {{customerInfo.address}}"
};
});
HTML
<div ng-controller="Controller">
<my-customer info="naomi" stars="star1"></my-customer>
<hr>
<my-customer info="igor" stars="star2"></my-customer>
</div>
(function(angular) {
'use strict';
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', '$attrs', function($scope, $attrs) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.igor = { name: 'Igor', address: '123 Somewhere' };
//Here are the attr values
console.log($attrs.stars);
console.log($attrs.info);
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
starts: '=stars',
customerInfo: '=info'
},
//Associate controller
controller: 'Controller',
template: "Name: {{customerInfo.name}} Address: {{customerInfo.address}}"
};
});
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-directive-isolate-production</title>
</head>
<body ng-app="docsIsolateScopeDirective">
<div ng-controller="Controller">
<my-customer info="naomi" stars="star1"></my-customer>
<hr>
<my-customer info="igor" stars="star2"></my-customer>
</div>
</body>
</html>