$ scope变量在函数中访问时丢失值

时间:2015-12-15 21:08:43

标签: angularjs

我的console.log语句显示$ scope.selectedUser在条件期间有一个值,并且在我的函数$ scope.showUserPets中未定义。这怎么可能,我该如何解决?

var myApp = angular.module("Pets");
myApp.controller("MainCtrl", function($scope, $routeParams, $http) {
    $scope.selectedUser = $routeParams.user;
    if ($scope.selectedUser && $scope.info) {
       console.log("Has user and doing showUserPets: " + $scope.selectedUser); // user = user1
       $scope.showUserPets();
    }

   $scope.init = function() {
      // Sets $scope.info via $http.get
   }

   $scope.showUserPets() = function() {
      for (var i = 0; i < ($scope.info).length; i++) {
           console.log($scope.selectedUser + " " +  $scope.info[i].user); // $scope.selectedUser is undefined.
      }

1 个答案:

答案 0 :(得分:0)

试试这个:

   $scope.showUserPets($scope.selectedUser);



   /* notice that in you code $scope.showUserPets() ... don't use () in the
   $scope variable */
    $scope.showUserPets = function(selected) {
      for (var i = 0; i < ($scope.info).length; i++) {
           console.log(selected + " " +  $scope.info[i].user); // $scope.selectedUser is undefined.
      }