Not able to add attribute in directive in angular

▼魔方 西西 提交于 2019-12-13 02:59:45

问题


I have this code in my 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) {

This works fine

But i want to add attribute instead of remove attribute based on boolean like this

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

But this is not working.

I thing i need to recompile element after adding but i don't know how to do it


回答1:


Try adding the attribute in template function of the directive definition.

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



回答2:


jQlite (angular's "jQuery" port) doesn't support lookup by classes.

find() - Limited to lookups by tag name

So you should try querySelector

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


来源:https://stackoverflow.com/questions/28666974/not-able-to-add-attribute-in-directive-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!