我想我只是在做一些愚蠢的事情,但是我想要在我附加指令的HTML元素上访问自定义属性但它不起作用。我见过其他人使用范围。$ eval但我似乎无法让它工作。
这是我尝试过的(jsfiddle here:https://jsfiddle.net/u5d3gfny/1/):
<!DOCTYPE html>
<html ng-app="AngAttrTest">
<head>
<title>Bootstrap 3</title>
</head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<a href="#" id="my-modal" class="btn btn-success fcvt-btn-save" nextModalId="fileFormatModal" chain-modal>Continue</a>
<div id="appendMe"/>
<script>
var app = angular.module('AngAttrTest', []);
app.directive('chainModal', ['$document', function($document){
return {
link: function(scope, elem, attrs) {
elem.bind('click', function() {
$('#appendMe').append("This works, ID: " + attrs.id + "<br/><br/>");
$('#appendMe').append("So does this, Class: " + attrs.class + "<br/><br/>");
$('#appendMe').append("But my custom Attribute nextModalId comes up undefined: " + attrs.nextModalId + "<br/><br/>");
});
}
}
}]);
</script>
</body>
</html>
我也尝试用这个替换我的链接功能:
link: function(scope, elem, attrs) {
elem.bind('click', function() {
var nextModalId = scope.$eval(attrs.nextModalId);
$('#appendMe').append("This works, ID: " + attrs.id + "<br/><br/>");
$('#appendMe').append("So does this, Class: " + attrs.class + "<br/><br/>");
$('#appendMe').append("But my custom Attribute nextModalId comes up undefined: " + nextModalId + "<br/><br/>");
});
}
这看起来应该很简单,但我无法弄清楚我做错了什么傻瓜。谢谢!
答案 0 :(得分:0)
当指令用作属性时,必须以snake-case声明。要解决......
更改nextModalId
:
<a href="#"
id="my-modal"
class="btn btn-success fcvt-btn-save"
nextModalId="fileFormatModal"
chain-modal>
Continue
</a>
至next-modal-id
:
<a href="#"
id="my-modal"
class="btn btn-success fcvt-btn-save"
next-modal-id="fileFormatModal"
chain-modal>
Continue
</a>
答案 1 :(得分:0)
问题在于elem.bind函数不是指令。我用这种方式改变了代码:
var app = angular.module('AngAttrTest', []);
app.directive('chainModal', ['$document', function($document){
return {
link: function(scope, elem, attrs) {
elem.bind('click', { id: attrs['id'], class: attrs['class'], nextModalId: attrs['nextModalId'] }, function(event) {
$('#appendMe').append("This works, ID: " + event.data.id + "<br/><br/>");
$('#appendMe').append("So does this, Class: " + event.data.class + "<br/><br/>");
$('#appendMe').append("But my custom Attribute nextModalId comes up undefined: " + event.data.nextModalId + "<br/><br/>");
});
}
}
}]);