简体   繁体   English

仅在console.log()之后更新角度模型

[英]Angular model updates only after a console.log()

UPDATE 更新

I found that the problem was not with Angular, but a mistake in the update function in the node server controller. 我发现问题不是出在Angular,而是节点服务器控制器中更新功能的错误。 The fix is below, and I'm leaving the question here to help those that may have made the same mistake I did. 该修补程序在下面,我将问题留在这里,以帮助那些可能犯了与我相同的错误的人。

ORIGINAL QUESTION 原始问题

Angular model doesn't change when a property is changed in a form. 在表单中更改属性时,角度模型不会更改。 Code: 码:

<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>

When I select the check box, either going to true or false, and submit the form, the original model is sent to the server, not updated. 当我选中复选框(是true还是false)并提交表单时,原始模型将发送到服务器,而不是更新。 I then inserted ng-click="logDj() to log the model and see what is happening. However, when I click it, the model updates. What I'm looking for is a more detailed explanation of why this is? 然后,我插入ng-click="logDj()来记录模型并查看发生了什么。但是,当我单击它时,模型就会更新。我要寻找的是为什么这样的更详细说明?

Here is the 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);
    };
  }
]);

I thought maybe because the property didn't previously exist that it may cause this behavior, but even when the property is populated when retrieved, the model refuses to change. 我以为是因为该属性以前不存在,所以可能会导致这种现象,但是即使检索时填充了该属性,该模型也会拒绝更改。

I'm using the default set-up for MEAN.JS by Yeoman; 我正在使用Yeoman的MEAN.JS默认设置。 if that helps at all. 如果有帮助的话。

EDIT This only affects the checkboxes. 编辑这仅影响复选框。 The other fields change the model values. 其他字段更改模型值。

Just my guess, try initialize the object before accessing it; 只是我的猜测,请在访问对象之前尝试对其进行初始化。 it's unclear how you set the other fields (which work), maybe they are set in the scope directly, not under dj namespace 目前尚不清楚如何设置其他字段(哪些起作用),也许它们是直接在作用域中设置的,而不是在dj名称空间下设置的

$scope.authentication = Authentication;
$scope.dj = {};
.
.
.
$scope.update = function (isValid) {
    var dj = $scope.dj;

to verify, add a line of debugger within the update method, and inspect the dj object; 验证,在update方法中添加一行调试器,并检查dj对象;

$scope.update = function (isValid) {
    debugger; // it should create a breakpoint in chrome dev tools
    var dj = $scope.dj;

hope this helps 希望这可以帮助

After following the data around as it goes through the process of updating the Dj model, I found what I was missing. 在跟踪更新Dj模型过程中的数据之后,我发现了我所缺少的东西。 It has nothing to do with Angular, but rather the server.controller in node. 它与Angular无关,而与node中的server.controller无关。 Although the create function works without modification, the update function in the controller must be updated to match the model. 尽管创建功能无需修改即可工作,但必须更新控制器中的更新功能以匹配模型。 When the PUT request is sent, the middle where populates the req with the Dj model when a valid ID is in the params. 发送PUT请求时,当有效ID位于参数中时,中间将使用Dj模型填充请求。

var djsPolicy = require('../policies/djs.server.policy'),
    djs = require('../controllers/djs.server.controller');

module.exports = function (app) {
  // Djs collection routes
  app.route('/api/djs').all(djsPolicy.isAllowed)
    .get(djs.list)
    .post(djs.create);

  // Single dj routes
  app.route('/api/djs/:djId').all(djsPolicy.isAllowed)
    .get(djs.read)
    .put(djs.update)
    .delete(djs.delete);

  // Finish by binding the dj middleware
  app.param('djId', djs.djByID); // HERE! };

This is then passed to the update function, where I should have matched the fields in the request body with those in the Dj model. 然后将其传递给更新函数,在这里我应该将请求正文中的字段与Dj模型中的字段进行匹配。 Original code: 原始代码:

exports.update = function (req, res) {

  var dj = req.dj;

  dj.title = req.body.title;
  dj.content = req.body.content;

  dj.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(dj);
    }
  });
};

The original code also had the field title, which made it appear as if the update function was working properly when testing in the browser and changing this field, but fail when marking the checkboxes. 原始代码还具有字段标题,这使它看起来好像更新功能在浏览器中进行测试并更改此字段时正常工作,但是在标记复选框时失败。 The working code is: 工作代码是:

exports.update = function (req, res) {
  var dj = req.dj;

  dj.title = req.body.title;
  dj.image = req.body.image;
  dj.images = req.body.images;
  dj.links = req.body.links;
  dj.categories = req.body.categories;
  dj.description = req.body.description;
  dj.guest = req.body.guest;
  dj.featured = req.body.featured;

  dj.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.json(dj);
    }
  });
};

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

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