在angular.js中的控制器之间共享变量

Gid*_*don 30 ajax global-variables angularjs

我是棱角分明的新手,我想知道如何在角度控制器之间共享一个变量.我正在使用以下脚本 -

在Main.js中:

function MainCntl($scope) {
  ---code
}

function SearchCtrl($scope, $http) {
    $scope.url = 'http://10.0.0.13:9000/processAdHoc';
    $scope.errorM = "No results";     
    $scope.search = function() {

        $http.post($scope.url, { "data" : $scope.keywords}).
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
            $scope.result = data; 
            alert('yes');
        })
        .
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;   
            alert('no');
            $scope.result = "failed";
        });
    };
}
Run Code Online (Sandbox Code Playgroud)

在Index.html中

<body ng-controller="MainCntl" >
---code
<div ng-controller="SearchCtrl">
     <form class="well form-search">
     <div class="ui-widget">
          <label for="tags"></label>
          <a ng-click="search()"><input type="image" src="../../images/search1.png" class="searchbox_submit" /></a>
          <input ng-model="keywords" placeholder="Shadow Search" id="tags" class="input-medium search-query rounded" /> 
     </div>
     </form>
</div>
---code
<p ng-model="result">
     {{result}}
</p>
</body>
Run Code Online (Sandbox Code Playgroud)

一切都适用于我正在发送数据和收到回复的ajax,我的问题如下:

在SearchCtrl函数中,我有一个名为$ scope.result的变量,后来在Index.html中引用.如果我将包含该变量的html代码插入到SearchCtrl控制器中,它可以正常工作,但如果它在MainCtrl控制器中则不起作用.如何在控制器之间共享此变量.

谢谢你

Sha*_*.io 70

使用服务并将其注入两个控制器并将范围变量引用到服务变量.

例:

angular.module("yourAppName", []).factory("myService", function(){

  return {sharedObject: {data: null } }

});

function MainCtrl($scope, myService) {
  $scope.myVar = myService.sharedObject;
}

function SearchCtrl($scope, $http, myService) {
  $scope.myVar = myService.sharedObject;
}
Run Code Online (Sandbox Code Playgroud)

在您的模板中执行:

{{myVar.data}}
Run Code Online (Sandbox Code Playgroud)

See an example 使用Angular v1.1.5

将它放在内部对象中的原因是为了保留引用,如果保持它没有"sharedObject",并且更改该对象,则绑定将指向旧引用,并且不会在模板中显示任何内容.

  • @Gidon我编辑了答案,请参阅jsbin上添加的示例.此外,ShaiRez的代码中存在错误. (2认同)