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

nar*_*spr 8 javascript angularjs angularjs-directive angularjs-scope

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

HTML应如下所示:

<div ng-app="test">
    <custom-directive attr1="value1" attr2="value2"></custom-directive>
</div>
Run Code Online (Sandbox Code Playgroud)

和js:

   var app = angular.module('test', [ ]);
    app.directive("customDirective", function(){
        return {
            restrict: 'E',
            scope: ???,
            controller: function(){
                console.log("print attributes value: " + attr1 + ", " +  attr2 );
            }
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

期望控制台输出应该是:

print attributes value:value1,value2

任何的想法?谢谢!

PzY*_*Yon 5

在您的指令中,您可以定义要访问和使用的范围对象(属性),如下所示:

app.directive("customDirective", function(){
    return {
        restrict: 'E',
        scope: {attr1: "=", attr2: "="},
        link: function(scope, elem, attr){
            console.log("print attributes value: " + attr.attr1 + ", " +  attr.attr2 );
        }
    };
Run Code Online (Sandbox Code Playgroud)

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

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

有关更多信息,请参阅以下链接:http: //weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope