本文介绍了在angular.js控制器之间的共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的角度,我不知道我怎么能在角控制器之间共享的变量。我用下面的脚本 -

I'm new to angular and I'm wondering how I can share a variable between controllers in angular. I'm using the following scripts -

在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";
        });
    };
}

index.html中

In 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>

一切都可以很好地处理我发送数据和接收响应的AJAX,我的问题如下:

Everything works well with the ajax I'm sending data and receiving a response, my question is as follows:

在SearchCtrl功能我有一个变量名为$ scope.result就是后来被称为index.html中。如果我插入HTML code包含可变进SearchCtrl控制器,它工作正常,但如果是在MainCtrl控制器,这是行不通的。我如何可以共享控制器之间的变量。

In the SearchCtrl function I have a variable called $scope.result that is later referred to in Index.html. If I insert the html code that contains that variable into the SearchCtrl controller it works fine but if it is in the MainCtrl controller it does not work. How can I share this variable between the controllers.

由于提前

推荐答案

使用一个服务,它注入到两个控制器,并参阅您的范围瓦尔到服务变量。

Use a service and inject it to both controllers and refer your scope vars to the services variable.

例如:

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;
}

在您的模板做的:

{{myVar.data}}

查看示例 使用角V1.1.5

Uses Angular v1.1.5

您把它放在一个内部对象的原因是preserve你的推荐,如果你把它没有共享对象,并更改该对象,你的绑定将指向旧的参考,不显任何在模板中。

The reason you put it in an inner object is to preserve your references, if you keep it without a "sharedObject", and change that object, your binding will be pointing to the old reference and wouldn't show anything in the template.

这篇关于在angular.js控制器之间的共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:31