如何将$ scope.someStuff响应值转换为变量?

问题描述 投票:-1回答:1

这是我的角度控制器:

angular
    .module('hameedApp', [])
    .controller('hameedController', function($scope, $http) {

        $http({
            method: 'GET',
            url: 'json.php'
        }).then(function(response) {
            $scope.contacts = response.data;

        }).catch(function(response) {
            console.log('error');
        })
    });

这是我的body标签的html:

<table class="table">
    <tr>
        <th>Name</th>
        <th>Phone No</th>
        <th>Email</th>
    </tr>
    <tr ng-repeat="contact in contacts">
        <td>{{contact.name}}</td>
        <td>{{contact.gsm}}</td>
        <td>{{contact.email}}</td>
    </tr>
</table>

<script>
    var test = {{contacts}}
    console.log(test);
</script>

我想在一个名为“test”的变量中获得{{contacts}}全数组json数据。

可能吗?

javascript html arrays angularjs json
1个回答
1
投票

角度概念是你放在$scope中的任何东西都无法在non-angular代码中直接访问。您可以做的是,您可以使用window对象将其分配给任何全局变量,如下所示。

angular
    .module('hameedApp', [])
    .controller('hameedController', function($scope, $http) {

        $http({
            method: 'GET',
            url: 'json.php'
        }).then(function(response) {
            $scope.contacts = response.data;
            window.contacts = response.data;
        }).catch(function(response) {
            console.log('error');
        })
    });

现在你可以在contacts以及angular代码中的任何地方访问non-angular

编辑

如果你想在contacts代码中获得non-angular,你必须使用callback机制来告诉你的non-angular代码有关更新的值。见下文

在你<head>,在method添加一个新的window像这样

<head>
  <script>
    ....
    ....
    window.updateContacts = function(contacts) {
      console.log(contacts);
    }
    ....
    ....
  </script>
</head>

现在你可以使用callback代码中的angular,如下所示

angular
    .module('hameedApp', [])
    .controller('hameedController', function($scope, $http) {

        $http({
            method: 'GET',
            url: 'json.php'
        }).then(function(response) {
            $scope.contacts = response.data;
            window.updateContacts(response.data);
        }).catch(function(response) {
            console.log('error');
        })
    });
© www.soinside.com 2019 - 2024. All rights reserved.