gpt4 book ai didi

angularjs - API调用新数据后 Angular View 未更新

转载 作者:行者123 更新时间:2023-12-02 20:11:16 24 4
gpt4 key购买 nike

我有两个控制器。在ng-view中加载索引页面时使用第一个控制器,并从数据库中检索10个对象。这部分工作正常。当在索引页面上提交表单时,将调用第二个控制器,该表单将过滤器提交给API并从数据库中检索10个新对象。我可以在客户端(console.log)中看到新对象,但是由于某些原因,ng-repeat不会刷新新数据。我是新手,可能缺少一些简单的东西(我希望如此)。

/* Controllers */

angular.module('myApp.controllers', []).
controller('IndexCtrl', function ($scope, $http, employees){
employees.getAllEmployees().success(function(data){
$scope.employees = data.employees;
});
}).
controller('SearchFormCtrl', function ($scope, $http, employees) {
$scope.submitForm = function(){
employees.getFilteredEmployees($scope.form).success(function(data){
console.log('data: ' + JSON.stringify(data.employees));
$scope.employees = data.employees;
});
};
});

/* Services */

angular.module('myApp.services', []).
constant('version', 'Version: 0.1').
factory('employees', function ($http) {
return {
getAllEmployees: function() {
return $http.get('/api/employees');
},
getFilteredEmployees: function(form){
return $http.post('/api/employees/filter/', form);
}
};
});


部分索引(用Jade编写):

| <div ng-include src="'partials/searchForm'"></div>
div(ng-repeat='employee in employees')
h3
a(href='/viewEmployee/{{employee.GEID}}') {{employee.fullname}}
h6
span {{employee.CGH_OFFCR_TTL_DESC}} | {{employee.JOBTITLE}} | {{employee.JOB_FUNCTION}} | {{employee.CGH_WORK_COUNTRY}}


搜索表单部分(用Jade编写)

div.well.well-sm
form(name='myForm', novalidate, ng-controller='SearchFormCtrl').form-inline
div.form-group
select(ng-model='form.cband').form-control
option C15+
option C12-14
option Other
button(ng-click='submitForm()').btn.btn-primary Filter

最佳答案

这是一个示例,显示如下:

angular.module('myApp.controllers', []).
controller('IndexCtrl', function ($scope, Employees){
$scope.employees = Employees.employees;
Employees.getEmployees();
}).
controller('SearchFormCtrl', function ($scope) {
$scope.submitForm = function(){
Employees.filterEmployees($scope.form);
};
}).
service("Employees", function($http){
var employees = {};
return {
getEmployees: function() {
$http.get('/api/employees').
success(function(data, status, headers, config) {
angular.copy(data.employees, employees);
});
},
filterEmployees: function(form) {
$http.post('/api/employees/filter/', form).
success(function(data){
angular.copy(data.employees, employees);
});
},
employees: employees
}
});


我认为您应该阅读范围,并了解谁以及如何创建范围。

ng-view,ng-if,ng-switch-when,ng-include,任何控制器和您的自定义指令(可选)都可以创建作用域。 ng-repeat也创建隔离的作用域,但这是特例。

解决问题的其他方法是使用事件($ on,$ broadcast,$ emit http://docs.angularjs.org/api/ng。$ rootScope.Scope)。

关于angularjs - API调用新数据后 Angular View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19770203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com