Angular: parent/sub components
parent / sub component example where sub components using a common controller function; or "reference by id" example (John Lindquist):
by dandoyon
HTML
<script src="http://code.angularjs.org/angular-1.0.0rc8.js"></script>
<my-component id="foo">
<!-- This shows how to "wire-up" your app. "foo" is the controller of "myComponent"-->
<sub-component ng-model="someMessage" ng-dblclick="foo.apiFunc(someMessage)"></sub-component>
<sub-component ng-model="anotherMessage" ng-dblclick="foo.apiFunc(anotherMessage)"></sub-component>
</my-component>
JavaScript
var myApp = angular.module('myApp', []);
myApp.directive('myComponent', function () {
return {
restrict:'E',
controller:function ($scope, $attrs) {
var ctrl = this;
ctrl.apiFunc = function (message) {
alert(message);
};
//expose the controller's api through the $scope using the id
$scope[$attrs.id] = ctrl;
}
}
});
myApp.directive('subComponent', function () {
return {
restrict:'E',
replace:true,
template:'<input>'
}
});