Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Below is my code on my appController:

//  appController.js

$scope email = "[email protected]";

$scope.emailInfo = "[email protected]";

//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 "[email protected]".

};

console.log($scope.email); // this will print "[email protected]", but I 

//want it to print "[email protected]" as I triggered the ng-click function to 

//apply the change.


console.log($scope.emailInfo); //this will print "[email protected]".

What do I miss? Any thought?

like image 548
zihaow Avatar asked Mar 26 '26 12:03

zihaow


1 Answers

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 = "[email protected]";
      $scope.emailInfo = "[email protected]";
      $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">[email protected]</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>
like image 75
Danny Fardy Jhonston Bermúdez Avatar answered Mar 29 '26 06:03

Danny Fardy Jhonston Bermúdez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!