2016-11-07 242 views
0

我試圖從出方訪問變量 「K」 的$範圍功能

.controller('AboutCtrl', ['$scope','$http', function($scope,$http) { 
    var k =""; 
    $scope.search = function() { 
    // $scope.searchText will give the search terms 
    k = $scope.searchText; 
    console.log(k); //has something 
    }; 
    console.log(k); // this is empty 
+0

這看起來相當不錯。首先,當你啓動控制器K將空..那麼一旦調用方法k將保存值 –

+0

'k = $ scope.searchText'該語句綁定到函數表達式'$ scope.search'的塊範圍,因此它在初始加載時不起作用。 – dreamweiver

+0

你覺得它應該如何工作? –

回答

0

使用$ rootScope爲此,rootScope是一個角度全局變量,您只需要注入依賴關係,就像您在下面的代碼中看到的一樣,並在控制之外使用它呃以及..

.controller('AboutCtrl', ['$scope','$http','$rootScope' function($scope,$http,$rootScope) { 
    // var k =""; use below method. 
    $rootScope.k = ""; 
     $scope.search = function() { 
     // $scope.searchText will give the search terms 
     $rootScope.k = $scope.searchText; 
     console.log($rootScope.k); //has something 
     }; 
     console.log($rootScope.k); // this is empty 
+0

我用它來表達我的感謝!我使用(.run),它的工作原理 – kuhle

1

這將是空的,直到你真的叫search功能,

app.controller("AboutCtrl", function($scope, $http) { 
    var k = ""; 
    $scope.search = function() { 
    // $scope.searchText will give the search terms 
    k = $scope.searchText; 
    console.log(k); //has something 
    }; 
    //this will print the value 
    $scope.print = function() { 
    alert(k); 
    } 

}); 

DEMO

0

你可以使用angular的服務。基本上你需要創建服務如下

app.service('svc', function() { 
    this.k = ""; 
    this.setK = function(value) { 
    this.k = value; 
    } 
    this.getK = function() { 
    return this.k; 
    } 
}); 

然後確保注入的服務,您的控制器

.controller('AboutCtrl', ['$scope','$http', function($scope,$http,svc) { 
    var k =""; 
    $scope.search = function() { 
    // $scope.searchText will give the search terms 
    k = $scope.searchText; 
    console.log(k); //has something 
    svc.setK(k); //saving k to the service 
    }; 
    console.log(k); // this is empty 
    k = getK(); //getting k from the service 
相關問題