繁体   English   中英

如何在angularjs中获取自定义标签的属性值?

[英]How to get attribute value of a custom tag in angularjs?

我正在尝试使用angularJs创建自定义标记 此标记具有名为data的属性。 data获得它的价值<skillviz data="{{user.info}}"></skillviz> user.info是一个JSON对象。 但是当我尝试在我的指令定义中访问此data属性时,我得到了undefined 这样做的正确方法是什么?

HTML代码

<div id="info-box" ng-repeat="user in users | orderBy:orderProp">            
          <div id="skill-block">
            <skillviz height="50" data="{{user.skills}}"></skillviz>
          </div>
      </div>

users是在控制器中声明的JSON类型对象。 所以基本上users将是一个列表(数组)

{"first_name": "Tifanny",

        "last_name": "Maxwell",
        "skills": [
            {"name": "Java", "score": 4.8, "color" : "red"},
            {"name": "C++", "score": 4.0, "color" : "blue"},
        ]
    }, 

services.js

angular.module('yott', []).directive('skillviz', function () {
return {
    restrict: 'E',
    link: function (scope, element, attrs) {
        element.html("<script>alert(" + attrs['data'] + ")</script>");
        });
    }
  }
});

警告框弹出说未定义

假设您有以下标记:

<div ng-controller="MyController" data-id="someCustomValue">
</div>

现在,在您的控制器中,您可以执行以下操作来访问data-id

app.controller('MyController', function ($scope, $attrs) {
  console.log($attrs.id); // Prints 'someCustomValue'
});

使用$observe来观察属性的变化:

attrs.$observe('data', function(value) {
  console.log('data has changed value to ' + value);
});

$set改变价值:

attrs.$set('data', 'new value');

或者,您可以使用@ (绑定本地范围)传递/链接到指令范围, & (提供在父范围的上下文中执行表达式的方法)或= (设置双向绑定) - 在此解释

angular.module('yott', []).directive('skillviz', function () {
    return {
        restrict: 'E',
        scope { data: "=data" },
        link: function (scope, element, attrs) {
            element.html("<script>alert(" +scope.data + ")</script>");
            });
        }
      }
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM