Not able to add attribute in directive in angular

2019-09-02 05:26发布

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

2条回答
乱世女痞
2楼-- · 2019-09-02 06:00

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');
}
查看更多
▲ chillily
3楼-- · 2019-09-02 06:25

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;
      }
    }
  });
查看更多
登录 后发表回答