[英]ng-init only if value is null/undefined
有沒有一種使用ng-init
的方法,以便僅當ng-model
值為null或未定義時才運行它?
我有這個輸入
<input ng-model="entry.Value.Currency" type="text" placeholder="Currency">
如果entry.Value.Currency == null
我希望將"Currency"
值設置為“ USD”。 請注意,它可能包含完全不同的值,例如'EUR'
在這種情況下,我希望代碼不執行任何操作。
現在,我在該字段中鍵入的內容都會被刪除,這是因為.Currency
不存在/是未定義的。 如果有助於輸入的值,則始終保證entry.Value
存在/不為null。
嘗試將ng-init="entry.Value.Currency ='USD'"
到輸入字段,但這似乎什么也沒做。
我想在不初始化javascript中的Currency
變量的情況下完成此操作,因為可以動態添加輸入,並且它們添加到entry.Value
值可能有所不同。 我對每個輸入控件唯一了解的是entry.Value = {};
最適合您的是使用ngModelController
的指令
我寫了一個應該做你想要的東西,它的代碼是
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);
}
}
}
});
並查看實際運行情況,可以查看此JSFiddle
PS對不起,我花了很長時間才寫出來,所以我去吃了午飯😀
您可以使用ng-attr-placeholder="{{!entry.Value.currency?'USD':'something'}}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.