我最近开始学习angularjs,并且我没有尝试指令而且我有这个问题,我想通过属性将对象传递给指令然后使用它的属性。我的代码是这样的: 指令:
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return self.dataSource.controllers.count
}
func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
viewOne.html
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!");
}
}
}
})
的index.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>
当我在浏览器中查看页面时,指令模板不会显示 <directive-one ng-repeat="promo in promos |limitTo : 3" promoDetail="{{ promo }}" testAttr="{{ promo.title1 }}" ></directive-one>
属性中的任何内容。我还尝试了控制台日志记录promoDetail
它显示了数据,但是当我尝试promoDetail
时它返回undefined。我写的代码有什么问题?
答案 0 :(得分:1)
您必须将属性写入指令中的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,&#39; promo&#39;是整个对象,可在您的指令中使用。但是如果你想把一个字符串传递给你的指令,那就写成:
...testAttr="test"...
现在,在您的房产中,testAttr将进行“测试”,而不是变量测试。
文档:根据&#39;隔离指令的范围&#39; https://docs.angularjs.org/guide/directive
答案 1 :(得分:0)
您需要通过scope
return {
restrict: 'E',
scope: {
promoDetail: '=',
testAttr: '='
},
现在在html调用中,将值赋给变量,不带大括号。
<directive-one ng-repeat="promo in promos |limitTo : 3" promoDetail="promo" testAttr="promo.title1">
答案 2 :(得分:0)
事实证明,您在指令范围内编写的属性名称与您在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>