gpt4 book ai didi

javascript - 具有自定义属性的angularjs自定义指令

转载 作者:数据小太阳 更新时间:2023-10-29 04:13:38 27 4
gpt4 key购买 nike

我是 angularjs 的新手,我不知道这是否可行以及如何实现它。我想创建一个带有 Controller 的自定义指令,该 Controller 使用通过属性传递给它的信息。这是我想要实现的一个非工作示例:

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 );
}
}
};
});

期望的控制台输出应该是:

print attributes value: 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 );
}
};

您可以使用不同类型的绑定(bind):

  • = 用于双向绑定(bind)
  • @简单读取值(单向绑定(bind))
  • &用于绑定(bind)函数

查看以下链接了解更多信息: http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

关于javascript - 具有自定义属性的angularjs自定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26497231/

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