neXus neXus - 4 months ago 9
AngularJS Question

How to check if my AngularJS controller is located inside a form

I have a controller that I reuse in two different places, but I want the controller to be able to distinguish wether it is used in a page that edits the data or a page that just displays the data. The difference here is that on one page the controller is located inside an

<... ng-form="someForm">

(Actually, it is a partial html file that gets included; the controller is inside that partial)

Is it possible to detect whether a controller is located inside a form? If so, how?


I found out that I could create a directive that optionally requires form (not ng-form) and that you can check whether it is present or not in the link function.

    .directive('formAware', [function(){
        return {
            require: '^?form',
            template: ' <div>{{isPartOfForm ? "Inside the form" : "Outside of the form"}}</div>',
            link: function(scope, element, attrs, formCtrl) {
                scope.isPartOfForm = (formCtrl !== null);

The directive can be placed inside an ng-form (displaying the text "Inside the form"):

<div ng-form="myForm">
    <div form-aware></div>

or without an ng-form (displaying the text "Outside of the form"):

    <div form-aware></div>