2015-05-17 138 views
0

我遇到範圍問題。我無法從控制器方法登錄訪問範圍屬性fullName。爲什麼?無法從控制器功能訪問示波器

App.controller('LoginController', ['$scope', 'LoginService', '$location', function(scope, LoginService, location) { 
    scope.fullName = "Full name"; 

    scope.login = function(data, scope) { 

     LoginService.login(data).then(function(data) { 

      scope.fullName = LoginService.getFirstName() + " " + LoginService.getLastName(); 
     }); 
    }; 

    scope.logout = function(data) { 
     LoginService.logout(); 
     location.path("/index.html#/login"); 

    }; 

}]); 

回答

2

也許是因爲在login您正在接收兩個參數。第二個scope覆蓋傳入控制器的那個。

0

我編輯它,現在它工作。 :) 我有另一個問題,fullName不會在此html中呈現。

它總是打印fullName,我在第二行設置,而不是登錄功能。

<li class="dropdown" ng-controller="LoginController"> 
         <a href="" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i>{{fullName}}<b class="caret"></b></a> 
         <ul class="dropdown-menu"> 
          <li> 
           <a href="#"><i class="fa fa-fw fa-user"></i> Profile</a> 
          </li> 
          <li> 
           <a href="#"><i class="fa fa-fw fa-envelope"></i> Inbox</a> 
          </li> 
          <li> 
           <a href="#"><i class="fa fa-fw fa-gear"></i> Settings</a> 
          </li> 
          <li class="divider"></li> 
          <li > 
           <a href="" ng-click="logout()"><i class="fa fa-fw fa-power-off"></i> Log Out</a> 
          </li> 
         </ul> 
        </li> 
0

看到本作的工作示例(一般的方式)如何將數據從一個服務發送和返回數據 - 的jsfiddle:下面的代碼的https://jsfiddle.net/z5vd676x/及複印件。你能適應它,使其爲你的應用更加高效,並按照最佳實踐(即承諾,錯誤處理,縮小等):

var app = angular.module('myApp', []); 

app.controller('LoginController', function($scope, LoginService) { 
    $scope.fullName = "Full name"; 

    $scope.login = function(data) { 
     $scope.data =data; //store as $scope.data and pass it to the service : 
     $scope.fullName = LoginService.getFirstName($scope.data) + " " + LoginService.getLastName($scope.data); 

    }; 

}); 

//this is an example of a .service, you did not provide your code for this 
app.service('LoginService', function() { 
    this.getFirstName = function (data) { 
     if (data === '123') 
      return 'John'; 
     else 
      return 'Mike'; 
    }; 

    this.getLastName = function (data) { 
     if (data === '123') 
      return 'Winkle'; 
     else 
      return 'Santos'; 
      }; 
}); 

的index.html(例如使用)

<div ng-app="myApp" ng-controller="LoginController"> 
     <input type="text" ng-model="findName"> <!--bind the search text--> 
     <button type="button" ng-click="login(findName)">Search</button> 

<!--show the initial value below and update it when the LoginService returns your data --> 
       <h3>Name: {{fullName}}</h3> 

    </div>