Reputation: 17657
How does one add a pure html fragment during a post link phase in directive? I am able to locate the element that I want to add to, just don't know which method or how to add it. Is it appendChild or insertAdjacentHTML or something else?
I am trying to add indicator that field is required in a label
Here is html
<label id="street">{{addressName}} Address:</label>
Here is what I have in a link function
function link(scope, element, attrs, model) {
var addressLabel = element[0].querySelector("#street");
// add this to label("<sup>*</sup>");
}
How can I add fragment <sup>*</sup>
into label element?
Update:
Based on Samir's comment here is how it looks right now
(function (angular) {
'use strict';
angular
.module('app')
.directive('srAddressEditor',srAddressEditor);
srAddressEditor.$inject = [$compile];
function srAddressEditor($compile) {
var controllerId = 'addressEditCtrl';
var controller = ['$scope', '$q', "addressEditDataSvc", "lodash", addressEditCtrl];
var directive = {
require: '?ngModel',
templateUrl: '/app/shared/addressEditor/addressEdit.html',
scope: {
address: '=',
addressName: '@',
requiredFields: '@' // comma delimited list of required fields street,zipCode,city,stateCode,countryCode
},
//compile: compile,
link: link,
controller: controller
};
return directive;
function link(scope, element, attrs, model) {
var requiredFields = (scope.requiredFields || "");
if (requiredFields != "") {
requiredFields = requiredFields.split(",");
} else {
requiredFields = [];
}
requiredFields.forEach(function (fieldName) {
var label = element[0].querySelector("#lbl_" + fieldName);
label.innerHTML = label.innerHTML + "<sup class='req'>*</sup>";
});
var compiled = $compile(element[0].innerHTML)(scope);
element.replaceWith(compiled);
element = compiled;
}
function addressEditCtrl($scope, $q, addressEditDataSvc, lodash) {
}
//bunch of code
}
})(angular);
Upvotes: 0
Views: 307
Reputation: 31787
Another solution would be create a directive just for the label
For example
Javascript (angular)
var app = angular.module('app', []);
app.directive('myLabelDirective', function() {
return {
link : function(scope, element, attrs) {
scope.addressName = 'Some address name';
scope.addition = '*';
},
template : '<label id="street">{{addressName}} Address: <sup>{{addition}}</sup></label>'
};
});
HTML
<body ng-app="app">
<my-label-directive></my-label-directive>
</body>
I'm not sure if this is the best approach for what you want, but I think it's kind easier and cleaner than just appending the text you want to append.
Here's the plunker in case you want to see it http://plnkr.co/edit/YP0AXtcx3GiBDbYPNKkp?p=preview
Upvotes: 1