我最近开始学习angularjs,并且我没有尝试指令而且我有这个问题,我想通过属性将对象传递给指令然后使用它的属性。我的代码是这样的:指令:
app.directive("directiveOne", function() {
return {
restrict: 'E',
scope: {},
templateUrl: 'js/views/viewOne.html',
link : function(scope, element, attrs){
scope.promoDetail = attrs.promodetail;
//scope.testAttr = attrs.testattr;
scope.clickMe = function(){
alert ('button clicked');
console.log("button clicked!");
}
}
}
})
viewOne.html
<div class="ui container" style="width: 800px; margin: 20px auto; background:url(../images/pic1.jpeg); background-position: center; background-size: cover; background-attachment:fixed; color: #f5f5f5; padding: 15px; text-align: justify ">
<!-- <img src="../images/pic1.jpeg" alt="image untrouvable" style="width:100%; height:300px; position: absolute; z-index: -100;"> -->
<h2>{{ promoDetail.title1 }} </h2>
<h3> {{ promo.title2}} </h3>
{{ testAttr}}
<p>
{{ promo.description }}
</p>
<button class="ui primary basic button" ng-click="clickMe()">SomeText{{ buttonText }}</button>
</div>
的index.html
<directive-one ng-repeat="promo in promos |limitTo : 3" promoDetail="{{ promo }}" testAttr="{{ promo.title1 }}" ></directive-one>
当我在浏览器中查看页面时,指令模板不会显示promoDetail
属性中的任何内容。我也试过控制台记录promoDetail
它显示数据,但当我尝试console.log(promoDetail.title1)
它返回undefined。我写的代码有什么问题?
您必须将属性写入指令中的scope-object:
app.directive("directiveOne", function() {
return {
restrict: 'E',
scope: {
promoDetails: '=', // '@' = string, '=' = object, '&' = function
testAttr: '@'
},
templateUrl: 'js/views/viewOne.html',
link : function(scope, element, attrs){
console.log(scope.promoDetail);
console.log(scope.testAttr);
scope.clickMe = function(){
alert ('button clicked');
console.log("button clicked!");
}
}
}
})
在你的HTML中:
...promoDetail="promo" testAttr="{{promo.title1}}"...
但是你不需要在额外的属性中传递promo.title1,'promo'是整个对象,并且在你的指令中可用。但是如果你想将一个字符串传递给你的指令,那就写成:
...testAttr="test"...
现在,在你的属性testAttr将是'test',而不是变量test。
文档:在“隔离指令的范围”下https://docs.angularjs.org/guide/directive
你需要通过scope
将变量传递给指令
return {
restrict: 'E',
scope: {
promoDetail: '=',
testAttr: '='
},
现在在html调用中,将值赋给变量而不使用大括号。
<directive-one ng-repeat="promo in promos |limitTo : 3" promoDetail="promo" testAttr="promo.title1">
事实证明,您在指令范围内编写的属性名称与您在html中传递给它的属性名称不完全相同。如果您使用CamelCase,就像我在范围内使用promoDetail="something"
一样,您可以在downCase中编写它。 directiveOne.js
app.directive("directiveOne", function() {
return {
restrict: 'E',
scope: {
promodetail: '=',
testattr: '@'
},
templateUrl: 'js/views/viewOne.html',
link : function(scope, element, attrs){
console.log(scope.promodetail.title1);
console.log(scope.testattr);
scope.clickMe = function(){
alert ('button clicked');
console.log("button clicked!");
}
}
}
})
的index.html
<directive-one ng-repeat="promo in promos |limitTo : 3" promoDetail="promo" testAttr="test"></directive-one>