<!DOCTYPE html>
<html ng-app='directiveApi'>
<head>
<script src="https://code.angularjs.org/1.3.10/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller='mainController'>
<button type="button" ng-click='directive1Ctrl.getFullName()'>Method1 of Directive1</button>
<button type="button" ng-click='directive2Ctrl.getFullName()'>Method1 of Directive2</button>
<button type="button" ng-click='test()'>test</button>
<button type="button" ng-click='directive1Ctrl.getFullNameReverse()'>test</button>
<some-directive api='directive1Ctrl' first-name='Scarlettt' last-name='scarlettLastNameFromParentController'></some-directive>
<some-directive api='directive2Ctrl' first-name='Alessandra' last-name='allessandraLastNameFromParentController'></some-directive>
</body>
</html>
angular.module('directiveApi', [])
.controller('mainController', function($scope) {
// The last name is injected from the parent scope
$scope.scarlettLastNameFromParentController = 'Johanson';
$scope.allessandraLastNameFromParentController = 'Ambrosio';
$scope.test = function() {
console.log($scope);
}
})
.directive('someDirective', function() {
return {
restrict: 'EA',
scope: {
api: '=', // Here two way binding for the directive's controller
firstName: '@', // First name is passed as a static string argument
lastName: '=' // Last name comes from the parent scope
},
//replace: true,
//controllerAs: 'api', // And the magic happens by using the controllerAs syntax
//bindToController: true,
controller: function($scope) {
var api = {};//this; // Instead of adding methods to the $scope (which you still can), add them to the this object
api.getFullName = function() {
console.log('Full Name: ' + $scope.firstName + ' ' + $scope.lastName);
};
api.getFullNameReverse = function() {
console.log('Reversed: ' + $scope.lastName + ' ' + $scope.firstName);
};
$scope.api = api;
},
link: function(scope, element, attributes, ctrl) {
// if you need this
}
}
});
/* Styles go here */