0

I created following form as a angular directive and try to access the firstname from parent controller. Please help me or guide me how to access directive form fields from inside MainCtrl.

HTML

 <pre>
      {{filter-frm| json}}
 </pre> 

 <div ng-controller="MainCtrl">
    <userform></userform>
 </div>

JS

.controller('MainCtrl', ['$scope',  function($scope){
    console.log($scope.filterForm.firstname) //How to get this ?
};

.directive('userform', [function () {
    return {
        restrict: 'E',
        scope: { formCtrl: '=' }
        template: '<div>'
            + '<form id="filterForm" ng-submit="login()">'
            + '<input name="firstname" ng-model="user.firstName">'
            + '</form> '
            + '</div>',
        link: function (scope, element, iAttrs) {
            var form = element.find('form');
            scope.formCtrl = form.controller('form');
        }
    };
}]);

2 Answers 2

2

If you add a name attribute to your form in your directive template, you will be able to access it via scope.formName. It should also bind the input fields values via scope.formName.fooInput.

In your case, adding name="filterForm" should do the trick:

template: '<div>'
    + '<form id="filterForm" name="filterForm" ng-submit="login()">'
    + '<input name="firstname" ng-model="user.firstName">'
    + '</form> '
    + '</div>',

Now you should be able to access scope.filterForm in the parent controller.

Param: name (optional); Type: string; Details: Name of the form. If specified, the form controller will be published into related scope, under this name.

from ngForm doc

Sign up to request clarification or add additional context in comments.

Comments

0

You have to bind the values of the field to variables of your controller's model. To do that, you have to expose the form fields as attributes of your directive.

See https://docs.angularjs.org/#!/guide/directive and how to use the scope field.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.