Angularjs指令隔离范围+单向数据绑定不适用于对象? [英] Angularjs directives isolated scope + one-way data-binding not working for objects?
问题描述
我已经创建了一个具有两个值的自定义指令。首先是配置对象,第二是数据对象。我修改我的指令中的配置和数据对象,它反映在父范围内。当我多次使用指令时,这会导致我错误。
我遵循 https://umur.io/angularjs-directives-using-isolated-scope-with-attributes/ ,我正在使用孤立的范围。
我想要单独的数据绑定在孤立的范围内的对象。无论我在指令功能上发生什么变化,都不应该反映在父级范围内。
以下是指令范围。
范围:{
config:& config,
dataObj:& dataObj
}
这里是如何在指令的链接功能中访问它
var config = scope.config();
var dataObj = scope.dataObj();
我假设通过引用传递在这里。
我正在加入JSbin。检查控制台对象的值正在变化并在父范围内反映。
https://jsbin.com/vagowe/edit?html,js,output
传递文本是单向绑定(@)
,传递对象是双向绑定(=)
将对象作为文本传递
< custom-directive config ={ config}}>< / custom-directive>
指令范围
范围:{
config:@
}
将链接转换回链接中的对象
var config = angular.fromJson(scope.config);
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.
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.
below is scope of directive.
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.
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(=)
passing object as text
<custom-directive config="{{config}}"></custom-directive>
scope in directive
scope: {
config: "@"
}
converting the string back to object in link
var config = angular.fromJson(scope.config);
这篇关于Angularjs指令隔离范围+单向数据绑定不适用于对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!