Currently, I am diving deep into AngularJS and focusing on mastering directives. My goal is to create a form input directive that can be easily reused across all my forms, simplifying the repetitive markup that comes with each form. However, I am facing a challenge with implementing two-way binding in my directive. The directive uses an isolated scope with its own internal property to store the input field's value. I have set up a watch on this internal property, successfully pushing the value from the isolated scope up to the controller's scope. What I am now trying to figure out is how to extract an initial value from the controller's scope and use it as the default value in my directive.
Check out my Plunker here: http://embed.plnkr.co/TbVB0q9DHhBCVLQ4U64W/script.js
When typing in the first input box, only the controller's scope property changes, not the directive's value. However, typing in the second input box updates both the directive and the controller's property.
I understand that passing the initial value through an attribute is a solution. Still, I am hopeful that I can retrieve the value from the controller's scope property using the ngModel reference within my directive.
AFTER ANSWER UPDATE:
If you're hesitant about learning directives and wonder why they are worth the effort, let me share one compelling reason. Here's an example:
Before using my directive for input fields:
<div class="form-group">
<label for="firstName" class="col-sm-6 col-md-4 control-label">First Name</label>
<div class="col-sm-6 col-md-8" ng-class="{'has-error': userForm.firstName.$invalid}">
<input type="text" id="firstName" name="firstName" placeholder="First Name" ng-model="muState.currentUser.firstName" class="form-control" required
popover="Cannot be blank" popover-trigger="{{{true: 'mouseenter', false: 'never'}[userForm.firstName.$invalid]}}" />
</div>
</div>
After applying my directive:
<ws-form-input input-name="firstName" input-label="First Name" input-placeholder="First Name"
ng-model="muState.currentUser.firstName"
required input-error="Cannot be blank"></ws-form-input>
Invest your time in learning directives. You'll save yourself from potential maintenance troubles down the road.