2017-11-01 8 views
0

私はそれはNGリピートディレクティブ内で定義されています自体要素ディレクティブで定義されたオブジェクトの属性があります。角度指令属性 - オブジェクトのプロパティ未定義

<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 

誰かがこの動作を説明してもらえますか?私は間違っている?

+0

あなたは '解析してみましたconsole.log($ attrs.elSel); '単にオブジェクトが文字列として出てくるのか、それとも他のデータ型であるのかを調べるだけです。 –

答えて

1

{{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>

+0

ありがとう、私はもう一度質問をさせていただきますように、すぐにあなたの答えを受け入れるよ、参照としてng-repeatからオブジェクトを渡す方法はありますか?中括弧なしではないので – Typo

+0

あなたのための例で私の答えを編集しました。 詳しい読解[こちら](https://docs.angularjs.org/guide/directive#isolating-the-scope-of-a- directive) – UncleDave