我正在开发 AngularJS (1.4.2) 应用程序的一部分,并试图了解如何在数据更改时从服务获取 Controller 更新数据。
我已经设置了this plunker来演示问题。我希望这个例子看起来不太复杂,但是在应用程序中,我有一个主 TableView ,就像 plunker 中的 TableView 一样,但有五个选项卡,每个选项卡都有自己的部分 html 文件和 Controller 。现在有一个服务可以保存所有字段数据,就像 plunker 中的那样。这个想法是,用户可以选中给定字段旁边的框来激活/停用它,因为它适合他们的数据,并且只有事件字段应该保留在数据库中,因此服务将过滤后的数据返回到 Controller 。 MainCtrl 中的 verifyFields() 函数模拟我的应用程序中的保存函数,并且 Controller 应该使用字段服务中的更新数据填充 newConnectionData 对象。
我已经添加了一个 pre 来显示当选中和取消选中复选框或当输入值更改时服务模型数据确实会更新。但到目前为止我还无法在主 Controller 中更新数据。
我尝试将 this stack overflow question that suggests returning a function rather than a primitive from the service 中的 plunker 解决方案单独合并到其中:
test.service('fields', function() {
...
var fields = this;
return {
...
activeOrders : function() { return filteredOrders },
activeShipment : function() { return filteredShipment },
activeActivity : function() { return filteredActivity }
}
test.controller('MainCtrl', ['$scope', '$rootScope', 'fields',
function($scope, $rootScope, fields) {
...
$scope.activeShipment = function () {
return fields.activeShipment();
};
$scope.activeActivity = function () {
return fields.activeActivity();
};
...和this one that suggests using a $watch :
$scope.$watch(function () { return fields.activeOrders() }, function (newVal, oldVal) {
if (typeof newVal !== 'undefined') {
$scope.activeOrders = fields.activeOrders();
}
});
$scope.newConnectionData = {};
...
$scope.verifyFields = function () {
$scope.newConnectionData = {
orders : $scope.activeOrders,
shipment : $scope.activeShipment(),
activity : $scope.activeActivity()
}
...
}
...但迄今为止都没有解决更新 Controller 中数据的问题。如果您有任何建议,我将不胜感激。感谢您的宝贵时间!
最佳答案
让服务将数据公开为属性。不要使 Controller 的使用过于复杂。直接使用就可以了。如果您需要在 html 中显示数据,请在 $scope
中添加对服务的引用。
test.service('fields', function() {
...
var fields = this;
return {
...
activeOrders : filteredOrders ,
activeShipment : filteredShipment ,
activeActivity : filteredActivity
在 Controller 中
test.controller('MainCtrl', ['$scope', '$rootScope', 'fields',
function($scope, $rootScope, fields) {
$scope.fields = fields;
在模板中
{{fields.activeShipment}}
关于javascript - AngularJS:在保存到 Controller 之前从服务获取更新的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31685134/