2013-06-02 108 views
9

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

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

警告框弹出一个列表(阵列)说不确定

+0

我只是改变了'element.html( ““);''到警报(ATTRS [ '数据']);',那么它为我工作。 http://plnkr.co/k7VCGMpYISBkm5iOtTjp –

回答

4

使用$observe观察更改属性:

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

而且$set改变值:

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

或者,也可以通过/它链接到使用@指令范围(绑定本地作用域),&(提供了一种方法中的上下文中执行的表达式父作用域)或=(建立双向绑定) - 解释here

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

另外,它是由'ATTRS [“数据”]'或'attrs.data'访问属性值的所有权利。请参阅[示例](http://docs.angularjs.org/guide/directive#Attributes)。 –

+1

应该有一个分号scope'后'和'= data'应该是'= data',或简单地'='。 –

20

比方说,你有以下标记:

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

现在在你的控制器,你可以做以下的访问数据ID

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

这是无效的 –

相关问题