无法在 angular 中的指令中添加属性

Not able to add attribute in directive in angular

我的指令中有这段代码

   compile: function compile (tElement, tAttributes, transcludeFn) {

        if (tAttributes.drag == 'false') {
            tElement.find('.myclass').removeAttr('draggable');
        }

        //attrs.$set('ngModel', 'new value');
        return {
            pre: function preLink (scope, element, attributes, controller, transcludeFn) {
                // Pre-link code goes here
            },
            post: function postLink (scope, element, attributes, controller, transcludeFn) {

这个很好用

但我想添加属性而不是像这样基于布尔值删除属性

        if (tAttributes.drag == 'true') {
            tElement.find('.myclass').attr('draggable');
        }

但这不起作用。

我想我需要在添加后重新编译元素,但我不知道该怎么做

jQlite(angular 的 "jQuery" 端口)不支持 类 的查找。

find() - Limited to lookups by tag name

所以你应该试试querySelector

if (tAttributes.drag == 'true') {
    tElement[0].querySelector('.myclass').attr('draggable');
}

尝试在指令定义的模板函数中添加属性。

module.run(function ($templateCache, $http) {
    $http.get('__templateURL__')
      .then(function (response){
        $templateCache.put('__templateID', response.data)
      })
  });

module.directive('x', function ($templateCache) {
    return {
      template: function (tEl, tAttrs) {
        var template = $($templateCache.get('__templateID')); 
        if (tAttrs.drag == 'true') {
          template.find('.myclass').attr('draggable');
        }
        return template[0].outerHTML;
      }
    }
  });