bunny
bunny

Reputation: 2027

how to access element in directive?

I have a html page in which there is a directive(child html) inside as below. I want to do input validation of input1 and input2 in directive(child html) for the button in parent html, but I don't know how I can access the input1 and input2 in child (directive). I would like to know what is the right way to access input1 and input2? Thanks in advance!!

Parent html:

<div>

<child></child>
<button name="myButton" ng-disabled="????.myForm.input1.$invalid"><button>

</div>

Directive: child

<form name="myForm">

<input name="input1" required/>
<input name="input2" required/>

</form>

Upvotes: 1

Views: 54

Answers (2)

copia li
copia li

Reputation: 318

Try this:

Parent controller:

vm.myForm = {};

Parent Html:

<child my-form="vm.myForm"></child>
<button name="myButton" ng-disabled="vm.myForm.input1.$invalid"><button>

Child directive:

scope: {
myForm: "="
}

Child HTML:

<form name="myForm">

    <input name="input1" required/>
    <input name="input2" required/>

</form>

Upvotes: 2

P.S.
P.S.

Reputation: 16384

You can $emit event to your parent controller and pass needed data.

Directive:

$scope.$emit('yourCustomEvent', 'Data to send');

And catch the event in you parent controller.

Parent controller:

$scope.$on('yourCustomEvent', function (event, data) {
  console.log(data); // will print "Data to send"
});

And in your case I advice you to include the button in your directive, it will be much easier to work with it.

Upvotes: 1

Related Questions