Changing ngModel value programatically from controller

Abhishek Bansal picture Abhishek Bansal · Aug 26, 2015 · Viewed 7.9k times · Source

I wish to modify value of an ngModel variable from my controller. However it doesn't seem to be reflecting in views. I have seen few other questions on SO but none worked for me. I want a solution where I do not need to create a new directive for this. I have also tried to wrap the change in $scope.$apply without success.

Here is plunkr demonstrating the issue.

Here is code from plunkr

JavaScript Controller:

    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>

Answer

sma picture sma · Aug 26, 2015

Remove the ng-model from the button and remove the $scope.$apply from the change handler:

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