<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="Ctrl">
<div class="parent-1" ng-controller="parentCtrl1">
<color-btn clickcb="makeRequest(event)"></color-btn>
</div>
<div class="parent-2" ng-controller="parentCtrl2">
<color-btn clickcb="makeRequest(event)"></color-btn>
</div>
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
angular.module('app', []).controller('Ctrl', function() {
}).controller('parentCtrl1', function($scope, $http, $log) {
$scope.makeRequest = function(event) {
return $http.get('data.json');
};
}).controller('parentCtrl2', function($scope, $http) {
$scope.makeRequest = function(event) {
return $http.get('/not/an/api/call');
};
}).directive('colorBtn', function($log) {
return {
replace: true,
link: onLink,
template: '<button ng-click="request($event)">Request</button>',
scope: {
onClick: '&clickcb'
}
}
function onLink(scope, el, attrs) {
scope.request = function($e) {
$log.debug('Request start');
el.removeClass('error').removeClass('success');
if (scope.onClick !== undefined) {
scope.onClick({
event: $e
})
.then(success, error);
}
};
function success(response) {
$log.debug('Success response', response);
el.addClass('success');
}
function error(response) {
$log.debug('Errror response', response);
el.addClass('error');
}
}
});
.error {
background-color: red;
color: white;
}
.success {
background-color: green;
color: white;
}
{
"key1": "value1",
"key2": "value2"
}