2
我有两个控制器。当在ng-view中加载索引页面时使用第一个控制器,并从数据库中检索10个对象。这部分工作正常。当在索引页面上提交表单时调用第二个控制器,该表单向API提交过滤器,并从数据库中检索10个新对象。我可以在客户端看到新的对象(console.log),但由于某些原因,ng-repeat不会使用新数据进行刷新。我是新来的角,可能缺少一些简单的东西(我希望)。API调用新数据后角度视图不会更新
/* 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);
}
};
});
指数部分(写在玉):
| <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}}
搜索表单部分(写在玉)
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
两个控制器中的'$ scope'可能不同。你可以用'console.log($ scope。$ id)'来测试它。 Angular中的范围对于控制器或指令是分层的。如果你可以提供更多的代码(例如'partials/searchForm'),更具体地说包含'ng-controller'的元素,我们可能会更具体。 –
@NikosParaskevopoulos你是对的。我几分钟前也意识到这一点。 $范围是不同的。我想我需要使用服务作为控制器之间的桥梁。将API数据库调用放在服务本身中,还是仅使用服务来保存“过滤器”属性并让控制器进行API数据库调用会更有意义? –
我会在服务中打电话。实际上,我会建议一个'员工'服务,知道如何处理和处理这两个调用,'api/employees'和'api/filter'。 –