角度指令属性 - 对象属性未定义

时间:2017-11-01 16:13:52

标签: javascript angularjs angularjs-directive

我有一个在element指令中定义的对象属性,它本身是在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

有人可以解释一下这种行为以及我做错了吗?

1 个答案:

答案 0 :(得分:1)

您将{{element}}作为字符串传递 - 这是{{variable}}所做的。

在短期内,这将解决它:

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

这是将对象传递给指令的最小示例:

&#13;
&#13;
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)
    }
  }
});
&#13;
<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>
&#13;
&#13;
&#13;