Angular JS update input field after change

前端 未结 5 1565
被撕碎了的回忆
被撕碎了的回忆 2021-01-30 20:26

I\'m trying to build a simple calculator in Angular in which I can override the total if I want. I have this part working but when I then go back to enter in a number in fields

5条回答
  •  一生所求
    2021-01-30 21:11

    I wrote a directive you can use to bind an ng-model to any expression you want. Whenever the expression changes the model is set to the new value.

     module.directive('boundModel', function() {
          return {
            require: 'ngModel',
            link: function(scope, elem, attrs, ngModel) {
              var boundModel$watcher = scope.$watch(attrs.boundModel, function(newValue, oldValue) {
                if(newValue != oldValue) {
                  ngModel.$setViewValue(newValue);
                  ngModel.$render();
                }
              });
    
              // When $destroy is fired stop watching the change.
              // If you don't, and you come back on your state
              // you'll have two watcher watching the same properties
              scope.$on('$destroy', function() {
                  boundModel$watcher();
              });
            }
        });
    

    You can use it in your templates like this:

     
  • Total
提交回复
热议问题