使用$ http.post,angularJs发送ng-init变量

时间:2017-04-05 16:00:39

标签: php angularjs angularjs-ng-init

如何使用PHP初始化$scope变量,以便稍后在$http.post请求中将其发送到服务器?我尝试使用ng-init,但它似乎不起作用:

<body ng-app="app" ng-controller="ctrl" ng-init="name='<?php echo $_GET['search']; ?>'">
    <pre>
        {{result}}
    </pre>
</body>
<script>
    var app = angular.module('app',[]);
    app.controller('ctrl',function($scope,$http){
        $http.post('post.php',{'var1': $scope.name,'var2':'test'}).then(function(response) { $scope.result = response.data; });
    });
</script>

1 个答案:

答案 0 :(得分:0)

也许尝试这样的事情:

<body ng-app="app" ng-controller="ctrl" ng-init="postMethod()">
    <pre>
        {{result}}
    </pre>
 </body>
<script>
    var app = angular.module('app',[]);
    app.controller('ctrl', function ($scope, $http) {
        $scope.myVar = '<?php echo $_GET['search']; ?>';
        $scope.postMethod = function(){
            $http.post('post.php',{'var1': $scope.myVar,'var2':'test'}).then(function(response) { $scope.result =      response.data; });
        };
    });
</script>