更新
我发现问题不在于Angular,而是节点服务器 Controller 中的更新功能出现错误。修复方法如下,我将问题留在这里以帮助那些可能犯了与我相同错误的人。
原始问题
当表单中的属性发生更改时,Angular 模型不会更改。代码:
<section class="container" ng-controller="DjsController" ng-init="findOne()">
<form name="djForm" class="form-horizontal" ng-submit="update(djForm.$valid)" novalidate>
<fieldset>
<div>.... other form fields </div>
<div class="form-group">
<label>Guest:</label>
<input name="guest" type="checkbox" ng-model="dj.guest">
</div>
<div class="form-group">
<label>Featured:</label>
<input name="featured" type="checkbox" ng-model="dj.featured">
</div>
<button type="button" ng-click="logDj()">Log it</button>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
</fieldset>
</form>
当我选择复选框(选择 true 或 false)并提交表单时,原始模型将发送到服务器,而不是更新。然后我插入 ng-click="logDj()
来记录模型并查看发生了什么。但是,当我单击它时,模型会更新。我正在寻找的是更详细的解释这是为什么?
这是 Controller :
angular.module('djs').controller('DjsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Djs',
function ($scope, $stateParams, $location, Authentication, Djs) {
$scope.authentication = Authentication;
// Clear forms
$scope.clear = ...
// Create new Dj
// $scope.create = ...
// Remove existing Dj
// $scope.remove = ...
// Update existing Dj
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'djForm');
return false;
}
// shows original model if logDj() is not fired
console.log($scope.dj);
var dj = $scope.dj;
dj.$update(function () {
$location.path('djs/' + dj._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Djs
//$scope.find = ....
// Find existing Dj
$scope.findOne = function () {
$scope.dj = Djs.get({
djId: $stateParams.djId
});
};
$scope.logDj = function() {
console.log($scope.dj);
};
}
]);
我想也许因为该属性以前不存在,所以可能会导致此行为,但即使在检索时填充该属性,模型也拒绝更改。
我正在使用 Yeoman 的 MEAN.JS 默认设置;如果这有帮助的话。
编辑 这仅影响复选框。其他字段更改模型值。
最佳答案
只是我的猜测,在访问对象之前尝试初始化该对象;目前还不清楚如何设置其他字段(哪些有效),也许它们是直接在范围中设置的,而不是在 dj 命名空间下设置的
$scope.authentication = Authentication;
$scope.dj = {};
.
.
.
$scope.update = function (isValid) {
var dj = $scope.dj;
为了验证,在 update 方法中添加一行调试器,并检查 dj 对象;
$scope.update = function (isValid) {
debugger; // it should create a breakpoint in chrome dev tools
var dj = $scope.dj;
希望这有帮助
关于javascript - Angular 模型仅在 console.log() 之后更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35707950/