如何用html部分的表达式更新ng-model的值



为什么不使用表达式更新ng-model的值。在ng-model被定义之前,值得到更新

值将在phase2或phase3发生变化时立即更新

<input type="text" name="phase1" value="{{phase2 - phase3}}" ></input>

值不会更新

<input type="text" name="phase1" value="{{phase2 - phase3}}" ng-model="phase1"></input>

所以我想写一个指令,它将评估指令内的表达式,并更新输出到模型,

这是html它看起来像

<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;
            }
        };
});

该指令仅在加载时评估,但我想不断更新/观察作为依赖字段(phase2 &phase3)的变化。

我可以从控制器更新值,但我想从html。请帮助我,如果它可能或反对的工作角

谢谢大家我知道我想做什么。这是我最后一个简单但有用的指令:)

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>

为了持续地观察阶段2/3的变化,您可以使用$scope。美元的手表功能。

像这样的东西将为您工作:

link: function (scope, element, attr, controller) {
         scope.$watchCollection('[phase1,phase2]', function() {
            //whatever you want to do over here            }

和作用域中传递phase1和phase2值

This will watch the  value expression and update the same when value will change
myApp.directive('myModelValue', function(){
return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                model: '=ngModel',
                value: '@myValue'
            },
            link: function (scope, element, attr, controller) {
                scope.$watch('value',function(newValue){
                      console.log(newValue);
               });
            }
        };
});
here value is a local scope so it will watch the expression 

最新更新