I'm trying to provide a convention, or standard, for a parent controller to communicate with a directive in Angular.
Basically the directive will have a "settings" object containing callbacks and initial data received from the controller, and an "api" object containing public functions.
I've created a service called "gabby" but it doesn't do much, just a convenience.
HTML
<div ng-app="myApp" ng-controller="appCtrl">
<my-dir settings="myDirSettings" api="myDirApi"></my-dir>
</div>
Parent Controller
angular.module('myApp').controller('appCtrl', function($scope) {
$scope.myDirSettings = {
onStart: function() {
//start the logic
},
defaultName: 'My App Name'
};
$scope.someClick = function() {
$scope.myDirApi.fetchData();
};
});
Directive
Just Angular angular.module('myApp').directive('myDir', function() {
return {
controller: 'myDirCtrl',
scope: { settings: '<', api: '=' }
};
});
Or with the Gabby Service
angular.module('myApp').directive('myDir', function(gabby) {
return {
controller: 'myDirCtrl',
scope: gabby.scope()
};
});
Directive's Controller
Just Angular angular.module('myApp').controller('myDirCtrl', function($scope) {
angular.extend($scope, {
onStart: function() {},
onSubmit: function() {},
defaultName: 'John'
}, $scope.settings);
$scope.api = $scope.api || {};
$scope.api.clearValues = function() {
//do magic things
};
$scope.api.fetchData = function() {
//do magic things
};
$scope.api.getValues = function() {
//do magic things
};
$scope.onSomeKeyPress = function() {
$scope.onStart();
};
});
Or with the Gabby Service
angular.module('myApp').controller('myDirCtrl', function($scope, gabby) {
gabby.for($scope)
.settings({
//These are the default settings for the directive,
//allowing the reader to easily understand what can
//be passed to the directive
onStart: function() {},
onSubmit: function() {},
defaultName: 'John'
})
.api({
//These are the public functions of the directives
clearValues: function() {
//do magic things
},
fetchData: function() {
//do magic things
},
getValues: function() {
//do magic things
}
});
$scope.onSomeKeyPress = function() {
$scope.onStart();
};
});
More details: https://github.com/yellowblood/gabby
- Am I trying to solve an already solved problem?
- Do you think this approach is readable and clear?