Mike
Mike

Reputation: 2703

What's the Angular way to update the scope?

I have a simple two-way binding setup with angular, and I added a plain javascript function that updates the value based off of the "alt" tag of an image a user clicks on. The problem is that when I hit save, the data doesn't update until I click inside the textbox and add a space. What's the best way to get around this?

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

    angular.module('copyExample', [])
      .controller('ExampleController', ['$scope',
        function($scope) {
          $scope.master = {};

          $scope.update = function(user) {
            // Example with 1 argument
            $scope.master = angular.copy(user);
          };

          $scope.reset = function() {
            // Example with 2 arguments
            angular.copy($scope.master, $scope.user);
          };

          $scope.reset();
        }
      ]);
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
</head>

<body ng-app="copyExample">
  <div ng-controller="ExampleController">
    <form novalidate class="simple-form">
      Name:
      <input type="text" ng-model="user.name" id="name" />
      <br />
      <img src="http://placehold.it/100&text=John" onclick="changeText(alt)" alt="John" />
      <br />
      <button ng-click="reset()">RESET</button>
      <button ng-click="update(user)">SAVE</button>
    </form>
    <pre>form = {{user | json}}</pre>
    <pre>master = {{master | json}}</pre>
  </div>
  <script>
    function changeText(value) {
      document.getElementById('name').value = value
    }
  </script>
</body>

</html>

Upvotes: 0

Views: 117

Answers (1)

lwalden
lwalden

Reputation: 803

working fiddle - http://jsfiddle.net/lwalden/b2p7pu7g/

If you are already using Angular then don't write a plain vanilla javascript function for the image click event - use Angular.

Also it's recommended not to use the alt attribute in this way. You could use a data- attribute instead.

Additional attributes within a tag to pass values to a function

Upvotes: 1

Related Questions