我编写了一个验证指令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);
但我不明白为什么当 Controller validationRegexps
上的变量更改时不触发 $observe
回调(当 regexp 时触发 ng-repeat 的回调)
变量已更改):
$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
值或 表达式
并在每个摘要周期进行计算,其中 $observe
采用插值
表达式,如{{validationRegexps}}
。
attr.$observe
仅当您将 attribute
与内插内容 {{}}
结合使用时才起作用。
HTML
<div ng-pattern="regexp" multiple-pattern="{{validationRegexps}}"></div>
关于javascript - 为什么值改变时没有触发 `attr.$observe`回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619048/