我在做什麼:如果用戶輸入一個值,在按鈕單擊時,我的JS調用一個服務從外部JSON檢索數據,並對輸入的值對JSON執行搜索如果找到匹配項,則顯示「員工記錄」。Angular從外部JSON對象搜索值
HTML
<body ng-app="sampleapp">
<div ng-controller="emp">
<form class="form-inline">
<div class="form-group">
<label>Enter Employee Number:</label>
<input type="text" class="form-control" ng-model="searchemp">
</div>
<button class="btn btn-primary" ng-click="doSearch();">Search</button>
</form>
<div emp-details ng-if="empno!=undefined"></div>
</div>
<body>
JS
var app = angular.module('sampleapp',[]);
app.controller("emp", ["$scope", "empService", function($scope, empService) {
$scope.doSearch = function() {
empService.findemployeeById($scope.searchemp ,function(r){
$scope.quesData = r.empno;
$scope.empname = r.empname;
$scope.sal = r.sal;
$scope.deptno = r.deptno;
$scope.hiredate = r.hiredate;
$scope.dob = r.dob;
});
};
}]);
app.service("empService",['$http','$log', function($http,$log) {
this.findemployeeById = function(empno,cb) {
$http({
url: 'assets/data.json',
method:'GET'
}).then(function(resp){
$log.log(resp.data);
cb(resp.data)
}, function(resp){
console.error("Error Occuerd");
});
};
}]);
app.directive("empDetails", function() {
return {
templateUrl:"emp-details.html"
};
});
Data.Json
{
"quesData": [{
"id": 1,
"empname": "John",
"sal":"3000",
"deptno":"TRI",
"hiredate":"10-June-2016",
"dob":"14-June-1990"
},
{
"empno": 2,
"empname": "asdasd",
"sal":"3000",
"deptno":"TRI",
"hiredate":"10-June-2016",
"dob":"14-June-1990"
}]
}
我要搜索基於EMPNO數據。
Hi @Smith Lee在控制檯中,我可以根據輸入的數據查看數據。但templateURL沒有獲取數據。我如何顯示模板URL。請幫忙。 –
Hi @ Hardik一切工作正常,但在templateUrl中獲取相同的數據。就像我輸入1一樣,TemplateURL –
也顯示太晚了?我再次編輯了我的帖子。它工作正常。 :-) –