gpt4 book ai didi

javascript - Angular Directive(指令)属性 - 对象属性未定义

转载 作者:行者123 更新时间:2023-12-03 03:08:26 25 4
gpt4 key购买 nike

我在元素指令中定义了一个对象属性,该属性本身是在 ng-repeat 指令中定义的:

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

这是我的指令:

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>

关于javascript - Angular Directive(指令)属性 - 对象属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47059146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com