Angularjs 指令隔离范围 + 单向数据绑定不适用于对象? [英] Angularjs directives isolated scope + one-way data-binding not working for objects?

查看:28
本文介绍了Angularjs 指令隔离范围 + 单向数据绑定不适用于对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个自定义指令,它有两个值.第一个是配置对象,第二个是数据对象.我在我的指令中修改了这个配置和数据对象,它在父作用域中反映了它.当我必须多次使用指令时,这会导致我出错.

I have created a custom directive which has two values. first is config object and second is data object. I modify this config and data objects inside my directive which is reflecting it in parent scope. Which is causing me error when I have to use directive multiple times.

我关注了https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/ 并且我使用的是隔离范围.

I followed https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/ and I am using isolated scope.

我想要一种对隔离范围内的对象进行数据绑定的方法.无论我在指令函数中更改什么,它都不应该反映在父作用域中.

I want one way data binding for objects in isolated scope. Whatever I change in directive function it should not reflect in the parent scope.

以下是指令的范围.

scope: {
    config: "&config",
    dataObj: "&dataObj"
}

这是我如何在指令的链接函数中访问它

here is how I access it in the link function of directive

var config = scope.config();
var dataObj= scope.dataObj();

我假设这里发生了引用传递.

I am assuming that pass by reference is happening here.

我正在添加 JSbin.检查控制台 object 的值正在更改并反映在父作用域中.

I am adding JSbin. check the console the value of object is changing and reflecting in parent scope.

https://jsbin.com/vagowe/edit?html,js,output

推荐答案

传递文本为单向绑定(@),传递对象为双向绑定(=)

passing text is one-way binding(@) and passing object is two-way binding(=)

将对象作为文本传递

<custom-directive config="{{config}}"></custom-directive>

指令范围

scope: {
  config: "@"
}

将字符串转换回链接中的对象

converting the string back to object in link

var config = angular.fromJson(scope.config);

这篇关于Angularjs 指令隔离范围 + 单向数据绑定不适用于对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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