[英]Angular.js model defined in JavaScript, one property needs to be evaluated as a function
我已經在JS中定義了我的模型,如下所示:
$scope.requirement = {
id: function() {
if($scope.dada || $scope.lala) {
return $scope.dada
}
return $scope.haha
}
}
變量是無意義的,但假裝它們已定義(在我的情況下,這只是一個例子)。
然后在帶有Angular指令的HTML中,我輸入如下:
<input type="text" ng-model="requirement.id" placeholder="ID">
從函數返回的值不是價值requirement.id
。 如何傳遞上述函數,但讓Angular.js評估該函數並使用返回值?
編輯:
我嘗試了這個沒有用的方法:
$scope.requirement = {
id: null
}
if($scope.dada || $scope.lala) {
$scope.requirement.id = $scope.haha;
}
當我運行console.log(requirement)
該值已更改,但是它並不代表視圖中的新值。 視圖中的輸入仍顯示為null
如果進行雙向綁定,則需要將id
定義為具有一個參數的getter / setter函數。 因此,當值傳遞時,它將充當設置器,更新模型。 否則,它只會根據您的邏輯獲取當前值。
$scope.requirement = {
id: function(newId) {
if (arguments.length) {
$scope.dada = newId;
}
return ($scope.dada || $scope.lala) ? $scope.dada : $scope.haha;
}
}
您必須更新輸入元素並添加ng-model-options屬性。
<input type="text" ng-model="requirement.id" ng-model-options="{ getterSetter: true }" />
如果您只是在談論單向綁定,那么您就不需要使用getter / setter或ng-model。
<input type="text" value="{{requirement.id()}}" readonly />
ng-model是雙向綁定,定義方式為require.id返回一個函數對象(它不執行該函數),但更重要的是,當人們填寫您的輸入字段時,它將覆蓋該對象,因為您告訴過將輸入框的值放入require.id變量的角度。 如果只需要獲取值,請使用{{requirement.id()}}或更具可讀性的{{requirement.getId()}}。
如果確實需要通過函數進行雙向綁定,請使用Daniel的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.