如何在角度指令

时间:2015-06-16 16:59:39

标签: angularjs angularjs-directive

如何在指令的后期链接阶段添加纯html片段?我能够找到我想要添加的元素,只是不知道哪种方法或如何添加它。是appendChild还是insertAdjacentHTML还是别的什么?

我正在尝试在标签中添加指示字段

这是html

 <label id="street">{{addressName}} Address:</label>

以下是我在链接功能中的内容

function link(scope, element, attrs, model) {
  var addressLabel = element[0].querySelector("#street");
  // add this to label("<sup>*</sup>");
}

如何将片段<sup>*</sup>添加到标签元素中?

更新

基于萨米尔的评论,这里是它现在的样子

   (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);

1 个答案:

答案 0 :(得分:1)

另一种解决方案是为label

创建一个指令

例如

Javascript(有角度)

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>

我不确定这是否是您想要的最佳方法,但我认为它比仅附加您想要追加的文本更容易,更清晰。

如果您想看到http://plnkr.co/edit/YP0AXtcx3GiBDbYPNKkp?p=preview

,请使用以下内容