为什么双击字段后会在angularjs页面中显示数据
我正在从angularjs控制器获取数据:为什么双击字段后会在angularjs页面中显示数据,angularjs,Angularjs,我正在从angularjs控制器获取数据: $scope.findEmployeeById = function() { if( !angular.isUndefined($location.search().employeeId) ) { $.getJSON( servicefindEmployeeById+$location.search().employeeId, function( data ) { $sc
$scope.findEmployeeById = function() {
if( !angular.isUndefined($location.search().employeeId) ) {
$.getJSON( servicefindEmployeeById+$location.search().employeeId, function( data ) {
$scope.employee = data;
});
}
}
我在employee-detail.html页面上呈现$scope.employee,如下所示:
<html>
<body ng-init="findEmployeeById()">
<input type="text" ng-model="employee.firstName"/>
</body>
</htm>
问题陈述:
它仅在我在字段中单击,然后在字段外单击后显示数据
请说明我为什么要面对这个问题
谢谢。将
$timeout
注入控制器
$scope.findEmployeeById = function() {
if( !angular.isUndefined($location.search().employeeId) ) {
$.getJSON( servicefindEmployeeById+$location.search().employeeId, function( data ) {
$timeout(function(){
$scope.employee = data;
});
});
}
}
或者您可以使用$scope.$apply()
问题: 由于您正在使用
$.getJSON
并将角度$scope
包装在其中,因此摘要循环无法读取该更改。
解决方案1(首选):
使用,angular的
$http
而不是$。getJSON
对于json,您可以使用方法类型
$scope.findEmployeeById = function() {
if( !angular.isUndefined($location.search().employeeId) ) {
$http({method: 'JSONP', url: servicefindEmployeeById+$location.search().employeeId}).
then(function(data, status) {
$scope.employee = data;
}).
catch(function(data, status) {
console.log(data || "Request failed");
});
}
}
解决方案2(出于性能原因不推荐,但仍可能有效): 如果要使用
$.getJSON
,则可以使用$scope.$apply
并包装$scope.employee=data代码>在它里面
$scope.findEmployeeById = function() {
if( !angular.isUndefined($location.search().employeeId) ) {
$.getJSON( servicefindEmployeeById+$location.search().employeeId, function( data ) {
$scope.$apply(function () {
$scope.employee = data;
});
});
}
}
解决方案2的注意事项:
$scope.$apply(函数(){$scope.employee=data;})代码>仅运行
对于employee
,因为我包装了一个函数,这样更好
与运行完整摘要周期的$scope.$apply()
相比
再说一遍
当您调用findEmployeeById
函数时,这里有findEmployeeById()
我认为这可能是一个摘要问题。尝试使用$http.get(json_url)。然后((res)=>{$scope.employee=res.data;})
另一种方法是$scope.$apply()
.findeemployeebyid在employ-detail.html@Sravan的ng init中
$scope.findEmployeeById = function() {
if( !angular.isUndefined($location.search().employeeId) ) {
$.getJSON( servicefindEmployeeById+$location.search().employeeId, function( data ) {
$scope.$apply(function () {
$scope.employee = data;
});
});
}
}