从Ajax结果给ng-init赋值


Assigning value to ng-init from Ajax result

我有一个表单,有一个输入字段通过AJAX提交student id,我正在从AJAX请求中获取一些JSON结果。现在,AJAX请求返回的数据需要分配给表单下面的输入字段(phone)中的ng-init。请帮我如何将这个值赋给ng-init谢谢你!

<div ng-app="">
    <form id="std_form">
        <input type="text" name="sid" id="sid">
        <input type="submit">
    </form>
    <input type="text" name="phone" ng-model="phone" ng-init="" id="phone">
    Ph: {{phone}}
</div>
jQuery

$('#std_form').submit(function(e){
    e.preventDefault();
    var val = $('#sid').val();
    var dataString = "sid=" + val;
    $.ajax({
        type: "POST",
        url: "post_process.php",
        data: dataString,
        dataType: 'json',
        success: function(data){
            $('#phone').val(data.phone);
        }
    });
});

post_process.php

<?php
if(ISSET($_POST['sid'])) {
    $sid = $con->real_escape_string($_POST['sid']);
    $sql = "SELECT phone FROM std_detials WHERE sid = $sid";
    $result = $con->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $phone = $row['phone'];
    }
    $json = array('phone' => $phone);
    $json = json_encode($json);
    echo $json;
}
?>

您没有使用ng-model作为学生id字段。在角的时候,照角说的做。该代码混合了传统的PHP提交技术和通过Jquery进行的ajax调用。尽量消除这样的做法,并正确地欣赏框架。

试试这段代码。理解并应用。短暂:
我使用了Angular的$http post调用,而不是jquery的$.ajax。你可以保留相同的调用,也可以使用原生的angular调用。

删除一些不必要的标记。在学生号输入中增加了ng-model,在提交按钮中增加了ng-click功能,并对代码进行了结构化。如果你有一个单独的services.js文件,在那里添加服务代码,或者像我在这里的代码中所做的那样添加一个新服务。

基本上你不需要ng-init来解决这个问题。它应该在很少的情况下使用。请在这里阅读文档。https://docs.angularjs.org/api/ng/directive/ngInit

希望有帮助!如果有任何问题,请告诉我。

<div ng-app="myApp">
  <form id="std_form">
    <input type="text" ng-model="sid">
    <button ng-click="submitSid()"></button>
  </form>
  <input type="text" ng-model="phone">
  Ph: {{phone}}
</div>

JS

var app = angular.module('myApp', []);
app.controller('MyCtrl', ['StudentService', function(StudentService){
   $scope.submitSid = function(){
    var data = {sid: $scope.sid};
    StudentService.getStudentDetails(data).then(function(res){
        console.log(res);
        $scope.phone = res.phone; // Or change to res.paramName. Just check in console to confirm the res logged.
    })
}
}]);
 app.factory('StudentService', ['$http', '$httpParamSerializerJQLike',           function($http, $httpParamSerializerJQLike){
  var getStudentDetails = function(data){
  var params = $httpParamSerializerJQLike(data);
    return $http({
        method: "POST",
        url: "post_process.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
        data: params
    }).then(function(response){
      return response.data;
    });
}
return {
    getStudentDetails : getStudentDetails
}   
}]);