簡體   English   中英

角度指令屬性-對象屬性未定義

[英]Angular Directive Attribute - Object Property undefined

我在element指令中定義了一個object屬性,它本身是在ng-repeat指令中定義的:

<div ng-repeat="element in array">
    <my-directive el-sel="{{element}}>
        <something else>
    </my-directive>
</div>

這是myDirective:

app.directive('myDirective',function(){
  return {
    restrict:'E',
    scope: false,
    link: function($scope,$element,$attrs){

        console.log('element:' + JSON.stringify($attrs.elSel));
        console.log('href: ' + $attrs.elSel.href);  

    }
  }
});

控制台結果是:

element:"{\"name\":\"a name\",\"href\":\"#something\"}"
href: undefined

有人可以解釋這種行為以及我在做什么錯嗎?

您將{{element}}作為字符串傳遞-這就是{{variable}}所做的。

在短期內,這將解決此問題:

console.log('href: ' + JSON.parse($attrs.elSel).href);

這是將對象傳遞給指令的最小示例:

 var app = angular.module('app', []); app.controller('MainCtrl', function($scope) { $scope.something = { name: 'a name', href: '#somewhere' }; }); app.directive('myDirective', function() { return { restrict: 'E', scope: { elSel: '=' }, link: function($scope, $element, $attrs) { console.log($scope.elSel) } } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app" ng-controller="MainCtrl"> <my-directive el-sel="something"> </my-directive> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM