如何使用html部分中的表达式更新ng-model的值 [英] How to update value of ng-model with the expression in html part
问题描述
为什么 ng-model 的值没有用表达式更新.在 ng-model 被定义之前,值得到更新
Why value of the ng-model is not updated with the expression. Before ng-model is defined value get updated
当阶段2或阶段3发生变化时,值将立即更新
Value will be updated as soon as phase2 or phase3 changes
<input type="text" name="phase1" value="{{phase2 - phase3}}" ></input>
值不会更新
<input type="text" name="phase1" value="{{phase2 - phase3}}" ng-model="phase1"></input>
所以我想写一个指令来评估指令中的表达式并将输出更新为模型,
So I think of writing a directive which will evaluate the expression inside the directive and updated the output to model,
这是html,它看起来像
Here is html it will look like
<input type="text" name="phase1" ng-model="phase1" my-value="{{phase2 - phase3}}" my-model-value></input>
指令:
myApp.directive('myModelValue', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
value: '@myValue'
},
link: function (scope, element, attr, controller) {
scope.model = scope.value;
}
};
});
该指令仅在加载时评估,但我想随着依赖字段(阶段 2 和阶段 3)的变化不断更新/观察.
This directive evaluate only at load time, but I want to continuously update/watch as the dependent fields (phase2 & phase3) changes.
我可以从控制器更新值,但我想从 html 更新.请帮助我,它可能或反对 angular 的工作
I can update value from controller but I want to do it from html. Please help me, it it possible or against the working of angular
推荐答案
谢谢各位我知道我想做什么.这是我最后一个简单但有用的指令:)
Thanks guys I figure out what I wanted to do. Here is the my final simple but useful directive :)
app.directive('myModelValue', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function (scope, element, attr, controller) {
attr.$observe('myModelValue', function (finalValue) {
scope.model = finalValue;
});
}
};
});
用法:
<input type="text" ng-model="phase1" my-model-value="{{phase2 - phase3}}"></input>
<input type="text" ng-model="phase1.name" my-model-value="{{valid angular expression}}"></input>
这篇关于如何使用html部分中的表达式更新ng-model的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!