angularjs具有自定义属性的自定义指令
angularjs custom directive with custom attributes
我是angularjs的新手,不知道这是否可能,也不知道如何实现。我想创建一个带有控制器的自定义指令,该控制器使用通过属性传递给它的信息。这是我想要实现的一个非工作示例:
HTML应该看起来像:
<div ng-app="test">
<custom-directive attr1="value1" attr2="value2"></custom-directive>
</div>
js:
var app = angular.module('test', [ ]);
app.directive("customDirective", function(){
return {
restrict: 'E',
scope: ???,
controller: function(){
console.log("print attributes value: " + attr1 + ", " + attr2 );
}
}
};
});
预期控制台输出应该是:
打印属性值:value1,value2
知道吗?谢谢
在指令中,您可以定义要访问和使用的范围对象(属性),如下所示:
app.directive("customDirective", function(){
return {
restrict: 'E',
scope: {attr1: "=", attr2: "="},
link: function(scope, elem, attr){
console.log("print attributes value: " + attr.attr1 + ", " + attr.attr2 );
}
};
您可以使用不同类型的绑定:
- =用于双向绑定
- @只读取值(单向绑定)
- &用于绑定函数
有关详细信息,请参阅以下链接:http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope
进一步看,我发现了这个可能的问题解决方案。它与Plunker提出的非常相似,只是在语法上略有变化。这一个对我有效,但我不明白为什么普朗克提出的不。
app.directive('customDirective', function(){
return {
compile: function() {
return {
pre: function(scope, element, attributes) {
console.log("Value: " + attributes.attr1 + attributes.attr2);
}
};
}
}
});
指令可能会变得相当复杂。知道你的最终目标会得到更好的答案,但这是实现你所要求的最简单的方法:
var app = angular.module('test', []);
app.directive("customDirective", function(){
return {
link: function(scope, el, attr){
console.log("print attributes value: " + attr.attr1 + ", " + attr.attr2 );
}
}
});
Plunker
相关文章:
- 如何在自定义指令中获取计算的属性
- 向动态生成的DOM添加Angular自定义指令
- 自定义指令中的AngularJS ng模型
- 如何在html中以角度显示自定义指令的作用域
- 自定义指令模板中的AngularJS控制变量
- AngularJS通过自定义指令传递点击的项目
- 如何在angularjs中将多个作用域变量传递到自定义指令中
- 处理角度自定义指令中的onReady事件
- 为什么ng中的自定义指令在循环完成后重复运行
- 对于使用传递的数据计算的局部范围变量,角度绑定在自定义指令中不起作用
- Angular.JS自定义指令;不起作用
- 如何通过Angular中的$resource发送来自自定义指令的输入值
- AngularJS:如何访问自定义指令中的input[date]min属性
- AngularJS:ngRepeat作用域在具有隔离作用域和ngTransclude的自定义指令中失败
- 如何使用其他自定义指令中的元素标记作为另一个自定义指令的模板
- 如何限制自定义指令的可能属性值
- 动态网格作为自定义指令
- AngularJS - 在自定义指令中继承ngModel
- 调用另一个自定义指令的角度自定义指令
- 在 AngularJs 中验证自定义指令(我想让它成为必需的)