Using directive to indicate a textbox become a required field

####Objective####

  1. Example of ng-required
  2. Example of using instance attributes in link function in directive
  3. Example of having key:element mapping attribute

<!-- more --> <iframe style="margin: 20px 0; width: 100%; height: 300px" src="http://embed.plnkr.co/83wZy086dHDl1r9EDAcS" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

MarkupGithub
1
2
3
4
5
6
7
<form ng-submit="submit()" name="form">
<input type="checkbox" ng-model="partner" checked/>
Are you bringing along a partner?<br/>
Partner name:
<input type="text" ng-model="partnerName" xng-placeholder="{ 'required': partner }" ng-required="partner"/> <br/>
<input type="submit" value="save" ng-disabled="form.$invalid" class="btn"/>
</form>

AngularJSGithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
app.directive('xngPlaceholder', function () {
'use strict';
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.xngPlaceholder, function (newVal) {
element.removeAttr('placeholder');
var att = '';
angular.forEach(newVal, function (elm, key) {
att += elm ? (key + ' ') : '';
});
element.attr('placeholder', att);
}, true);
}
};
});