2017-03-22 107 views
0

下面是我的看法頁面NG-型號未在AngularJS NG-值工作

<form name="form"> 
    <label>Name</label> 
    <input name="name" type="text" ng-model='user.name' ng-value='emp.name' required /> 
    <span ng-show="form.name.$touched && form.name.$invalid">Name is required</span> 
    <button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button> 
</form> 

這是我的控制器

$scope.formUpdate = function() { 
    $scope.status = false; 
    $http({ 
    method : 'POST', 
    url : 'model/update.php', 
    data : $scope.user , 
    headers : {'Content-Type': 'application/x-www-form-urlencoded'}   

    }).then(function mySuccess(response) { 
    $scope.update = response.data; 
    console.log(response.data); 
    }, function myError(response) { 
    $scope.update = response.statusText; 

    }); 
}; 

當我使用數據:$scope.user在我的HTTP調用我在控制檯上得到空白值,但如果我使用數據:$scope.emp,那麼我永遠不會獲得輸入字段的更新值,而是獲取輸入字段的舊值。

+0

的目的是什麼,如果部份'NG-value'什麼是預期的結果? – Mistalis

+0

我正在用表單的幫助來實現更新邏輯,ng值從表中提取舊值,並且如果用戶想更新其字段值,那麼新值應該反映在DB中 –

+0

這是我猜到的,參見[**我的答案**](http://stackoverflow.com/a/42952719/4927984)。 – Mistalis

回答

0

試試這段代碼;

$scope.formUpdate = function(){ 
    $scope.status = false; 
    $scope.$applyAsync(); 

    $http({ 
    method : 'POST', 
    url : 'model/update.php', 
    data : $scope.user , 
    headers : {'Content-Type': 'application/x-www-form-urlencoded'}   

    }).then(function mySuccess(response) { 
    $scope.update = response.data; 
    $scope.$applyAsync(); 
    console.log(response.data); 
    }, function myError(response) { 
    $scope.update = response.statusText; 
    $scope.$applyAsync(); 
    }); 

    }; 
2

ng-value將給定的表達式綁定到元素的值。

正如我理解你的問題,你試圖初始化輸入值爲emp.name

您應該將輸入更改爲:

<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required /> 

ng-init docs

+0

謝謝米斯塔利斯,給出的解決方案對我無效 –

+0

@wasimbeg你能解釋一下「*沒有工作*」嗎?沒有更多的精準度,無法幫助你... – Mistalis