[英]Angular two-way binding not working as expected
This is my drective. 这是我的梦想。 value
is bound to a scope variable (session_number) and change is a function that get the current session_number and perform some checks. value
绑定到范围变量(session_number),change是获取当前session_number并执行某些检查的函数。
return {
restrict: 'A',
scope: { value: '=value',change:'&change' },
template: '<a href="javascript:;" class="counter-minus" ng-click="minus()">-</a>\
<input type="text" class="counter-field" ng-model="value" ng-change="changed()" ng-readonly="readonly">\
<a href="javascript:;" class="counter-plus" ng-click="plus()">+</a>',
link: function( scope , element , attributes ) {
// Make sure the value attribute is not missing.
if ( angular.isUndefined(scope.value) ) {
throw "Missing the value attribute on the counter directive.";
}
var min = angular.isUndefined(attributes.min) ? null : parseInt(attributes.min);
var max = angular.isUndefined(attributes.max) ? null : parseInt(attributes.max);
var step = angular.isUndefined(attributes.step) ? 1 : parseInt(attributes.step);
element.addClass('counter-container');
// If the 'editable' attribute is set, we will make the field editable.
scope.readonly = angular.isUndefined(attributes.editable) ? true : false;
/**
* Sets the value as an integer.
*/
var setValue = function( val ) {
scope.value = parseInt( val );
scope.change();
}
setValue(scope.value + 1);
}
}
I was wondering, why scope.change()
is executed before scope.value
. 我想知道为什么scope.change()
在scope.value
之前执行。 Because inside change()
I used session_number
that is bound to scope.value
, but always session_number
has a old value. 由于内部change()
我用session_number
绑定到scope.value
,但总是session_number
有一个旧值。 Its like when scope.change()
is executed, scope.value
did not change session_number variable yet. 就像执行scope.change()
时scope.change()
, scope.value
没有改变session_number变量。
I know what the problem is, thanks to this answer: 由于这个答案,我知道问题是什么:
AngularJS - directive with ng-transclude, no two-way binding AngularJS - 带有ng-transclude的指令,没有双向绑定
Two-2-way bidining using primitive values does not work as expected. 使用原始值的双向双向投标不能按预期工作。
Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (ie, form elements, ng-model) to a primitive (eg, number, string, boolean) defined on the parent scope from inside the child scope. 范围继承通常很简单,你通常甚至不需要知道它正在发生......直到你尝试双向数据绑定(即表单元素,ng-模型)到一个原语(例如,数字,字符串, boolean)在子范围内从父范围定义。
So I needed to change value
binding from primitive value to an object. 所以我需要将value
绑定从原始值更改为对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.