![](/img/trans.png)
[英]can we initialize value using ng-init from controller that value get from server side(php) to controller in angularjs
[英]Assigning value to ng-init from Ajax result
我有一个带有一个输入字段的表单,用于通过AJAX提交student id
,并且正在从AJAX请求中获取一些JSON结果。 现在,需要在表格下方的输入字段( phone )中将AJAX请求返回的数据分配给ng-init
。 请帮助我如何将此值分配给ng-init
。 谢谢!
的HTML
<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
。 您可以保持相同的通话或使用本机角度的通话。
删除了一些不必要的标记。在输入学生ID时添加了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
}
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.