从控制器以编程方式更改 ngModel 值

Changing ngModel value programatically from controller

我想从我的控制器修改 ngModel 变量的值。但是,它似乎并未反映在视图中。我在 SO 上几乎没有看到其他问题,但 none 对我有用。我想要一个不需要为此创建新指令的解决方案。我也曾尝试将更改包装在 $scope.$apply 中,但没有成功。

这里 plunkr 展示了这个问题。

这是来自 plunkr 的代码

JavaScript 控制器:

    app.controller('MainCtrl', function($scope) {
  $scope.Attachment = "something"
  $scope.change = function () {
      $scope.$apply(function() {
          $scope.Attachment = "otherthing";
      });
}

HTML:

<body ng-controller="MainCtrl">
    <section class="content" ng-app="offer">
        <div>
            <button name="change" ng-click="change()" ng-model="Attachment">change</button>
            <!-- <input name="Attachment" type="file" class="file_up" onchange="angular.element(this).scope().change(this)" ng-model="Attachment" /> -->
            <span>{{Attachment}}</span>

        </div>
    </section>
</body>

button 中删除 ng-model 并从更改处理程序中删除 $scope.$apply

http://plnkr.co/edit/lOyoTBxs0L0hMs20juLS?p=preview

勾选这个可能对你有帮助

function MyController($scope) {

  $scope.Attachment = "something"
  $scope.change = function() {

    $scope.Attachment = "otherthing";

  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app ng-controller="MyController">
  <button name="change" ng-click="change()" ng-model="Attachment">change</button>

  <span>{{Attachment}}</span>
</div>

您不需要使用 $scope.$apply()。我对 plunkr 进行了此更改以更新视图。

app.controller('MainCtrl', function($scope) {
  $scope.Attachment = "something"
  $scope.change = function () {
      $scope.Attachment = "other";
  }
});

最佳做法是绑定到对象属性而不是原始类型。
您正在绑定到一个原始类型且不可变的字符串。
您还应该删除 $apply,因为它不是必需的,因为您在 angular 引擎盖下,因此它会自动执行 $apply

如果您将数据添加为对象的 属性,您将不会再丢失引用:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  //this has changed:
  $scope.data = {
    Attachment: "something"
  }

  $scope.change = function() {
    //and $apply was removed from here
    $scope.data.Attachment = "otherthing";
  }
});

在 html 中,您只需更改:

<span>{{data.Attachment}}</span>

编辑虽然其他一些答案是正确的,但我认为您应该了解什么是绑定的最佳实践。更新后的plunker在这里