2016-11-07 93 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 
相关问题