触发ng-click功能时更改$ scope值

时间:2015-10-02 22:24:05

标签: javascript angularjs angularjs-scope angularjs-ng-click

我尝试在 ng-click函数中更改$ scope变量。但是似乎无法做到这一点。

以下是我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".

我想念什么?有什么想法吗?

2 个答案:

答案 0 :(得分:1)

<强>更新

$scope.emailOnClick函数会将$scope.emailInfo值分配给$scope.email变量。

如果单击“发送到服务器”按钮,您将看到已在控制台中发送的新值。

(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>

答案 1 :(得分:0)

您正在定义点击功能。尝试将您的while(error1==0);移到:

console.log