The directive known as "form aka ngForm" can be accessed using the form name.
<form name="testForm"> </form>
In the controller, we can use it like this:
$scope.testForm.$valid
And in HTML:
<button ng-show="testForm.$valid>
This turns the "form" directive into a UI component with accessible properties and methods (similar to non-HTML world)
Is there a standard approach to achieve such componentization for custom directives? For instance, I would like to create a directive called "list" with methods like "selectElement", "scrollToTop", "scrollToElement", "doSomething" etc. and utilize it in this way:
<list name="myList></list>
<button ng-click="myList.doSomething()">
and in another controller:
$scope.myList.scrollToTop();
I created a simple workaround based on what the "form" directive does - it exposes the public API of the directive in the scope under the variable defined by the name attribute:
app.directive('list', function () {
return {
restrict: 'E',
controller: function ($scope, $element, $attrs) {
// check if component name doesn't conflict with scope
if ($attrs.name) {
if (angular.isDefined($scope[$attrs.name])) {
throw "Error, component already defined with name: " + $attrs.name;
} else {
// publish controller object as public API
scope[$attrs.name] = {
date: new Date(),
myFunction: function(){}
};
}
}
},
template: '<ul></ul>'
}
});
Therefore:
<list name="myList"></list>
<button ng-click="myList.myFunction()">
and
$scope.myList.myFunction();
However, this does not work with isolated scope directives - a workaround could be passing the API object as an attribute with two-way binding as discussed in this question: How to call a method defined in an AngularJS directive?.
I also considered defining the API in a service, but it seems cumbersome - the service has to somehow be linked to the correct DOM element of the directive.
So my query is - what is the optimal pattern for accessing directive methods and properties from both HTML and other controllers to truly make directives act as UI components?
Or a simpler question - how can we access directive controllers from another controller or another expression in HTML similar to how we can do it with directives via "require"?