han*_*aad 5 javascript angularjs angularjs-directive angularjs-ng-model
我正在编写一个需要ngModel的指令,并添加格式化程序和解析器来操作该值.它工作得很好,但由于操作依赖于外部数据,我必须观看,我正在寻找一种方法来更新这款手表的模型值.我试着打电话$setViewValue但没有任何反应(因为$ viewValue没有改变??).
在下面的简单示例中,对"factor"的更改不会更新模型值:
angular.module('app', []).directive('multiply', multiplyDirective);
function multiplyDirective() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
factor: '=multiply'
},
link: function(scope, elem, attr, ngModel) {
ngModel.$formatters.push(function (value) {
return value / scope.factor;
});
ngModel.$parsers.push(function (value) {
return value * scope.factor;
});
scope.$watch('factor', function () {
// how to run the parsers pipeline to update modelvalue?
ngModel.$setViewValue(ngModel.$viewValue);
});
}
}
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.6/angular.min.js"></script>
<body ng-app ng-init="factor = 1; value = 1">
<input type="number" ng-model="value" multiply="factor" /> x
<input type="number" ng-model="factor" />
= {{ value }}
</body>Run Code Online (Sandbox Code Playgroud)
编辑:如果我调用内部$$parseAndValidate方法,它可以工作,但我想知道是否有一个公共API来强制执行更新.
编辑:我想通了,ngModel.$setViewValue(ngModel.$viewValue);改变了的行为1.3.0.使用1.2.x代码工作!
您的指令根本没有加载。您需要将模块名称指定给 ng-app,例如<body ng-app="app">. 之后ngModel.$setViewValue(ngModel.$viewValue)只要因子被修改就调用。
angular.module('app', []).directive('multiply', multiplyDirective);
function multiplyDirective() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
factor: '=multiply'
},
link: function(scope, elem, attr, ngModel) {
ngModel.$formatters.push(function (value) {
return value / scope.factor;
});
ngModel.$parsers.push(function (value) {
return value * scope.factor
});
scope.$watch('factor', function () {
// how to run the parsers pipeline to update modelvalue?
ngModel.$setViewValue(ngModel.$viewValue);
});
}
}
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-init="factor = 1; value = 1">
<input type="number" ng-model="value" multiply="factor" /> x
<input type="number" ng-model="factor" />
= {{ value }}
</body>Run Code Online (Sandbox Code Playgroud)