微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AngularJs将复杂数据传递到指令

我有以下指令:
<div teamspeak details="{{data.details}}"></div>

这是对象结构:

data: {
                details: {
                    serverName: { type: 'text',value: 'my server name' },port: { type: 'number',value: 'my port' },nickname: { type: 'text' },password: { type: 'password' },channel: { type: 'text' },channelPassword: { type: 'password' },autoBookmarkAdd: { type: 'checkBox' }
                }
}

并且我想它基于data.details对象内的数据生成链接
不幸的是它不工作,因为我不能访问任何内部的细节对象的值,但如果我传递一个简单的数据结构,如:

<div teamspeak details="{{data.details.serverName.value}}"></div>

我可以使用{{details}}访问它。

这是我的指令代码

App.directive('teamspeak',function () {
    return {
        restrict: 'A',template: "<a href='ts3server://{{details.serverName.value}}:{{details.port.value}}'>Teamspeak Server</a>",scope: {
            details: '@details',},link: function (scope,element,attrs) {
        }
    };
});

谢谢

阅读 Angularjs official site说明:

@ or @attr – bind a local scope property to the value of DOM
attribute. The result is always a string since DOM attributes are
strings. If no attr name is specified then the attribute name is
assumed to be the same as the local name. Given and widget deFinition of scope: { localName:’@myAttr’ },
then widget scope property localName will reflect the interpolated
value of hello {{name}}. As the name attribute changes so will the
localName property on the widget scope. The name is read from the
parent scope (not component scope).

所以你可以只发送一个字符串,传递一个对象,你需要设置一个双向的绑定使用=。

scope: {
        details: '=',

和你的HTML将看起来像

<div teamspeak details="data.details"></div>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐