为什么当值更改时不触发“attr.$observe”回调
Why isn't `attr.$observe` callback triggered when value is changed
我编写了一个验证指令multiple-pattern
,它需要几个验证正则表达式:
link: function (scope, elm, attr, ctrl) {
if (!ctrl) return;
let validators = [];
attr.$observe('multiplePattern', function (patterns) {
// doesn't get there after value change
var parsed = scope.$eval(patterns);
但我不明白为什么当控制器validationRegexps
上的变量更改时不触发$observe
回调(ng-repeat regexp
变量更改时触发回调(:
$scope.regexp = '^''S*$';
$scope.validationRegexps = {'nospaces': '^''S*$', 'nofirstnumber': '^[A-Za-z]'};
setTimeout(function () {
$scope.$apply(function () {
$scope.regexp = '[^abc]';
$scope.validationRegexps = {'noabc': '[^abc]'};
})
}, 5000);
用法:
<div ng-pattern="regexp" multiple-pattern="validationRegexps"></div>
$observe
的工作方式与$watch
相同。但这两者之间的区别在于$watch
取string
值或expression
并评估每个摘要周期,其中$observe
采用像{{validationRegexps}}
这样的interpolated
表达。
仅当您使用带有内值内容{{}}
attribute
时,attr.$observe
才有效。
.HTML
<div ng-pattern="regexp" multiple-pattern="{{validationRegexps}}"></div>
我刚刚检查了源代码,似乎对ng-pattern
值进行了特殊处理,可以在不指定插值的情况下正确处理$observe
:
var ALIASED_ATTR = {
'ngMinlength': 'minlength',
'ngMaxlength': 'maxlength',
'ngMin': 'min',
'ngMax': 'max',
'ngPattern': 'pattern'
};
forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
ngAttributeAliasDirectives[ngAttr] = function() {
return {
priority: 100,
link: function(scope, element, attr) {
//special case ngPattern when a literal regular expression value
//is used as the expression (this way we don't have to watch anything).
if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
if (match) {
attr.$set("ngPattern", new RegExp(match[1], match[2]));
return;
}
}
scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
// here the value is already interpolated
attr.$set(ngAttr, value);
});
}
};
};
});
与$observe
的其他用例的未插值相反:
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
// not interpolated value is passed down here
fn(attrs[key]);
}
});
return function() {
arrayRemove(listeners, fn);
};
}
相关文章:
- 使用AngularJs时,如何在img标记具有src-attr时设置数据src
- MutationObserver observe jquery append?
- 您的平台不支持RxJS-Array.observe
- jQuery中的attr()是否强制小写
- JQuery .attr();
- 获取一个javascript对象attr's
- Is jquery's attr() asynchronous?
- 使用返回函数sinde.attr()jquery元素
- jQuery place attr src在Chrome中不起作用
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 用jquery抓取图像SRC-attr
- JQuery:如果attr(左)等于0px,如何写入
- 从每个父对象获取attr,并为每个子对象设置attr
- Trouble with .attr('title')
- JS get元素之间的差异's属性与elem.getAttribute(attr)和elem[attr]
- jQuery.data('itemname')不工作,但jQuery.attr('data it
- attr()的回调函数
- 在什么情况下,Array.observe的“add”事件会触发
- 使用attr()和数据标记操作css
- 为什么当值更改时不触发“attr.$observe”回调