简体   繁体   English

ng-init仅当value为null / undefined时

[英]ng-init only if value is null/undefined

Is there a way to use ng-init so that it is only run if the value in ng-model is null or undefined? 有没有一种使用ng-init的方法,以便仅当ng-model值为null或未定义时才运行它?

I have this input 我有这个输入

<input ng-model="entry.Value.Currency" type="text" placeholder="Currency">

I would like the "Currency" value to be set to 'USD' if entry.Value.Currency == null . 如果entry.Value.Currency == null我希望将"Currency"值设置为“ USD”。 Note that it could contain a completly different value like 'EUR' in which case I want the code to do nothing. 请注意,它可能包含完全不同的值,例如'EUR'在这种情况下,我希望代码不执行任何操作。

As it is now whatever I type in the field just gets deleted, which I think is because .Currency does not exist / is undefined. 现在,我在该字段中键入的内容都会被删除,这是因为.Currency不存在/是未定义的。 If it helps the value of entry.Value is always guaranteed to exist / not be null. 如果有助于输入的值,则始终保证entry.Value存在/不为null。

Tried adding ng-init="entry.Value.Currency ='USD'" to the input field but that did not seem to do anything at all. 尝试将ng-init="entry.Value.Currency ='USD'"到输入字段,但这似乎什么也没做。

I would like to accomplish this without initializing the Currency variable in javascript as inputs can be added dynamically and what values they add to entry.Value may differ. 我想在不初始化javascript中的Currency变量的情况下完成此操作,因为可以动态添加输入,并且它们添加到entry.Value值可能有所不同。 The only thing I know for each input control is that entry.Value = {}; 我对每个输入控件唯一了解的是entry.Value = {};

What would suit you best is a directive that uses the ngModelController 最适合您的是使用ngModelController的指令

I've written one that should do what you want, the code for it is 我写了一个应该做你想要的东西,它的代码是

myApp.directive('currencyInit', function() {
  return {
    restrict: "A",
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      if (!ngModel) return;

      ngModel.$render = function() {
        if (ngModel.$modelValue == undefined || ngModel.$modelValue == null) {
          ngModel.$setViewValue('USD');
        }
        element.val(ngModel.$viewValue);
      }  
    }
  }
});

And to see it in action you can look at this JSFiddle 并查看实际运行情况,可以查看此JSFiddle

PS Sorry I took so long to write it I went out for lunch 😀 PS对不起,我花了很长时间才写出来,所以我去吃了午饭😀

您可以使用ng-attr-placeholder="{{!entry.Value.currency?'USD':'something'}}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM