无法在angular中添加指令属性

时间:2015-02-23 04:36:57

标签: angularjs angularjs-directive

我的指令

中有这个代码
   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');
        }

但这不起作用。

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

jQlite(angular的“jQuery”端口)不支持按类查找。

  

find() - 仅限于按标记名称查找

所以你应该试试querySelector

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