Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-click

Change $scope value when a ng-click function is triggered


I tried to change a $scope variable in ng-click function. But does not seem to be able to do that.

Below is my code on my appController:

//  appController.js

$scope email = "Awesome@example.com";

$scope.emailInfo = "great@example.com";

//emailOnClick() is a ng-click on DOM. It will be triggered when the user click a button, which is to save his email information

$scope.emailOnClick = function() {

  $scope.email = $scope.emailInfo;

  console.log($scope.email); //this will print "great@example.com".

};

console.log($scope.email); // this will print "awesome@example.com", but I 

//want it to print "great@example.com" as I triggered the ng-click function to 

//apply the change.


console.log($scope.emailInfo); //this will print "great@example.com".

What do I miss? Any thought?


Solution

  • Updated:

    $scope.emailOnClick function will assign the $scope.emailInfo value to the $scope.email variable.

    If you click in the «Send to server» button you'll see the new value that has been sent in the console.

    (function() {
      var app = angular.module("myApp", []);
      app.controller("Controller", ["$scope",
        function($scope) {
          $scope.email = "Awesome@example.com";
          $scope.emailInfo = "great@example.com";
          $scope.emailOnClick = function() {
            $scope.email = $scope.emailInfo; // Gets emailInfo value and assigns to $scope.email.
            console.log($scope.email);
          }
          $scope.sendToServer = function() {
            console.log($scope.email);
          };
          console.log($scope.email); // Initial state of $scope.email printed by default.
          console.log($scope.emailInfo); // Initial state of $scope.emailInfo printed by default.
        }
      ]);
    })();
    .email {
      background-image: linear-gradient(#FFF, #CCC);
      border: solid 1px #000;
      padding: 10px;
    }
    .emailInfo {
      background-image: linear-gradient(#FFF, #FBEE95);
      border: solid 1px #000;
      padding: 10px;
    }
    .option-clicked {
      font-weight: bold;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div data-ng-app="myApp">
      <div data-ng-controller="Controller">
        <div class="email">email: <span class="option-clicked">great@example.com</span>
    
        </div>
        <div class="emailInfo">emailInfo: <span class="option-clicked">{{email}}</span>
    
        </div>
        <button data-ng-click="emailOnClick()">Get email</button>
        <button data-ng-click="sendToServer()">Send to the server</button>
        <br />Result:
        <input id="txtEmail" data-ng-model="email" type="text" />
      </div>
    </div>