将属性数组发送到指令 [英] send array of attributes to directive

查看:23
本文介绍了将属性数组发送到指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了指令ng-attr,但我想要将属性数组发送到指令作为示例:

以我的指令为例:

myApp.directive('myElement', function(){返回 {限制:'E',要求:'ngModel',模板:'

'+'<!-- 我想在 div 元素上添加这个属性>'+'</div>',替换:真的,范围: {属性:'=属性'},}});

属性在控制器中如下:

$scope.attributes = {"class": "test", "id": "test", "style": "color: 'red'"}

那么,如何在指令中的元素中设置属性数组?

解决方案

In link function of your directive

link:function(scope, element, attrs){var templateElement = angular.element(element[0].firstChild)//这是你的模板div el.angular.forEach(scope.attributes, function(value, key){//如果要设置根元素attrs.$set(key, value)//如果要设置模板根divtemplateElement.attr(键,值)})}

I read about ng-attr for directive, but I want to send array of attributes to directive as example:

<myElement attributes="attributes"></myElement>

And my directive as example:

myApp.directive('myElement', function(){
 return {
    restrict: 'E',
    require: 'ngModel',
    template: '<div>' + 
              '<!-- I want to add this attributes on the div element>' + 
              '</div>',
    replace: true,
    scope: {
        attributes: '=attributes'
    },            
  }
});

And the attributes is in controller as the following:

$scope.attributes = {"class": "test", "id": "test", "style": "color: 'red'"}

So, How can I set array of attributes in element in directive ?

解决方案

In link function of your directive

link:function(scope, element, attrs){
     var templateElement = angular.element(element[0].firstChild) //this is you template div el.
      angular.forEach(scope.attributes, function(value, key){
           //if you want to set the root element
           attrs.$set(key, value)
           //if you want to set template root div
          templateElement.attr(key, value)
      })
}

这篇关于将属性数组发送到指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆