AngularJs 将复杂数据传递给指令 [英] AngularJs Passing complex data to directive

查看:29
本文介绍了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 对象中的数据生成一个链接.不幸的是它不起作用,因为不知何故我无法访问details对象的任何内部值,但是如果我向它传递一个简单的数据结构,例如:

and I want it to generate a link based on the data inside the data.details object. Unfortunately it doesn't work since somehow I cann't access any inner values of the details object, but if I am passing it a simple data structure like:

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

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

I can access it by using {{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官方网站解释:

@ 或 @attr - 将局部作用域属性绑定到 DOM 的值属性.结果总是一个字符串,因为 DOM 属性是字符串.如果未指定属性名称,则属性名称为假定与本地名称相同.范围的给定和小部件定义:{ localName:'@myAttr' },然后小部件范围属性 localName 将反映插值hello {{name}} 的值.随着 name 属性的变化,小部件范围上的 localName 属性.名字是从父作用域(不是组件作用域).

@ 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).

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

So you can send only a string, to pass an object, you need to set-up a bi-directionnal binding using =.

   scope: {
        details: '=',
    },

你的 HTML 看起来像

And your HTML will looks like

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

这篇关于AngularJs 将复杂数据传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆