如何从$ scope函数angular javascript外部访问变量?

时间:2016-11-07 06:37:48

标签: javascript angularjs

我正在尝试访问变量" k"从外部看$ scope函数

  .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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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