将数组绑定到AngularJS中的指令变量

Org*_*cat 32 html javascript angularjs

我正在尝试将数组放入模板中,以便我可以使用其中的个体值.我的问题是该属性在我的模板中变成一个字符串,所以它不再可以作为{{var [0]}}访问,而是返回"string"的第一个字符,通常是"["

以下是数据的简化设置:

"varForward": ["100", "1"],
"varBack": ["1", "100"]
Run Code Online (Sandbox Code Playgroud)

以下是与该数据交互的HTML文件的简化部分:

<my-customer-vars value="{{varForward}}">
    </address-numbers>
<my-customer-vars value="{{varBack}}">
    </address-numbers>
Run Code Online (Sandbox Code Playgroud)

最后这里是一个支持用我自己的东西替换自定义标签的部分:

directive('myCustomerVars', function($compile) {
    return {
        restrict: 'E',
        scope: {
            value: "@"
        },
        template:
        '<div>'+
          '<p class="body-text">Some stuff goes here</p>'+
          '<input type="text" name="firstinput" value="{{value[0]}}"> - '+
          '<input type="text" name="secondinput" value="{{value[1]}}">'+
        '</div>',
        replace: true
    }
});
Run Code Online (Sandbox Code Playgroud)

所以我在这里,如果我尝试使用值[0]我得到[如果我试图得到值[1]我得到"等等.在指令模板中使用数组有什么帮助吗?

Sha*_*.io 45

您需要将"@"更改为"="并传入不带{{}}的数组

像这样:

<my-customer-vars value="varForward">
    </my-customer-vars>
<my-customer-vars value="varBack">
    </my-customer-vars>
Run Code Online (Sandbox Code Playgroud)

指示:

directive('myCustomerVars', function($compile) {
    return {
        restrict: 'E',
        scope: {
            value: "="
        },
        template:
        '<div>'+
          '<p class="body-text">Some stuff goes here</p>'+
          '<input type="text" name="firstinput" value="{{value[0]}}"> - '+
          '<input type="text" name="secondinput" value="{{value[1]}}">'+
        '</div>',
        replace: true
    }
});
Run Code Online (Sandbox Code Playgroud)

之所以发生这种情况,是因为@中定义的directuve属性中的每个表达式都只被计算为字符串,而另一方面它被评估为绑定表达式.(用2路绑定,所以要小心).


Dan*_*ita 16

如果您不希望在指令中创建隔离范围(例如在创建自定义验证指令时),则可以将数组作为:

<my-customer-vars model="varForward">
Run Code Online (Sandbox Code Playgroud)

然后将指令的链接函数中的值读取为:

directive('myCustomerVars', function($compile) {
    return {
        restrict: 'E',
        link: function (scope, elm, attrs, ctrl) {
            var myVars = scope[attrs.model]; // <--- took a time to figure out
            console.log(myVars);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


Soh*_*oni 6

只是要添加到Danita的回复中,您将不得不$eval用于获取此范围变量:

只是改变

var myVars = scope[attrs.model]; 
Run Code Online (Sandbox Code Playgroud)

var myVars = scope.$eval(attrs.model); 
Run Code Online (Sandbox Code Playgroud)