如何在ng控制器之间传输数据(使用localhost链接api)

时间:2014-10-06 14:45:47

标签: javascript angularjs

我的tr上有一个按钮,按下我的tr后,我希望它将该tr内部的数据传输到下一个ng-controller。

我一直在寻找解决方案,但看起来我需要制作一个angular.module并将控制器连接在一起?或者它是否与localhostlink一起使用?你不需要解决它,我总是卡住,只是一些建议会很好。提前谢谢。

<div ng-controller="customersController">

    <table>
        <tr ng-click=getid(order) ng-repeat="x in Id">
            <td>{{ x.firstname }}</td>
            <td>{{ x.lastname}}</td>
        </tr>
    </table>

</div>

<div ng-controller="showinfo">

    <p>id:{{ x.firstname}}</p>
    <p>name:{{ x.lastname}}</p>


</div>

这是我的剧本     

     function customersController($scope, $http) {    


      $scope.getid= function (order) {



        };

        $http.get("localhostlink")
            .success(function (response) {
                $scope.Id = response;});
     }

2 个答案:

答案 0 :(得分:1)

您可以通过执行以下操作来使用同一个控制器:

<div ng-controller="customersController"> 
   <div>

        <table>
            <tr ng-click=getid(x) ng-repeat="x in Id">
                <td>{{ x.firstname }}</td>
                <td>{{ x.lastname}}</td>
            </tr>
        </table>

    </div>

    <div>

        <p>id:{{ currentSelection.firstname}}</p>
        <p>name:{{ currentSelection.lastname}}</p>


    </div>
</div>

使用脚本:

function customersController($scope, $http) {    

   $scope.currentSelection = {};

   $scope.getid= function (order) {

      $scope.currentSelection.firstname = order.firstname;
      $scope.currentSelection.lastname = ordername;  

   };

    $http.get("localhostlink").success(function (response) {
            $scope.Id = response;});
    }
}

答案 1 :(得分:0)

如果您确实需要控制器相互通信,请使用AngularJS提供的服务和$ rootScope(https://docs.angularjs.org/guide/services),然后将其注入需要通信的所有控制器。

以下是一个很好的例子:http://jsfiddle.net/simpulton/XqDxG/

&#13;
&#13;
myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};
    
    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});
&#13;
&#13;
&#13;

信用:http://onehungrymind.com/angularjs-communicating-between-controllers/