Javascript 角度/离子:使用ng repeat绑定到数组的更新视图
我是离子和角JS的新手。 尝试更新ng repeat指令中的集合(数组)时出错。Javascript 角度/离子:使用ng repeat绑定到数组的更新视图,javascript,angularjs,ionic-framework,Javascript,Angularjs,Ionic Framework,我是离子和角JS的新手。 尝试更新ng repeat指令中的集合(数组)时出错。 这是我的密码 视图: 工厂 .factory('TestFactory', ['Auth', function (Auth) { auth = Auth.get(); listObj = {}; auth.on('custom-trigger', function(index, value){ addElement(index, value); });
这是我的密码 视图: 工厂
.factory('TestFactory', ['Auth', function (Auth) {
auth = Auth.get();
listObj = {};
auth.on('custom-trigger', function(index, value){
addElement(index, value);
});
function addElement(index, value){
var obj = {}
obj.test=(value);
listObj[index].push(obj);
};
var TestFactory = {
getTest: function (index) {
if (typeof listObj[index] == 'undefined')
listObj[index] = [];
return listObj[index];
}
};
return TestFactory;
}])
对象测试列表是在“自定义触发器”触发后填充的:它工作正常,因为我可以在日志中看到新值。此触发器在应用程序开始时(多次,每次都正常工作)和服务器通知后(问题就在这里!!)触发。
问题是视图没有更新。我认为这是一个数据绑定问题。您可能需要通知控制器,
addElement
已触发。尝试添加另一个$broadcast
和侦听器:
工厂
.factory('TestFactory', ['$rootScope', 'Auth', function ($rootScope, Auth) {
// ...
function addElement(index, value){
var obj = {}
obj.test=(value);
listObj[index].push(obj);
// notify the app that `addElement` has occurred
$rootScope.$broadcast('elementAdded');
};
// ...
}])
控制器
.controller('TestCtrl', function ($scope, $stateParams) {
var param1 = $stateParams.param1;
$scope.testList = TestFactory.getTest(param1);
// listen for elementAdded event; re-get testList
$scope.$on('elementAdded', function(){
$scope.testList = TestFactory.getTest(param1);
});
});
它不起作用。事件工作,如果我这样做:console.log(TestFactory.getTest(param1)),我可以看到新值,但视图没有更新;在您的解决方案中,它起作用:$scope.$on('elementAdded',function(){$scope.testList=TestFactory.getTest(param1);$scope.$apply();});但是我不认为这是最好的解决方案。…@enfix我真的很惊讶你必须在
$on
中使用$apply
;但这可能是因为每次调用时,TestFactory.getTest
都返回对同一对象的引用。这是我最好的猜测。我也很惊讶。在应用程序的其他部分中,我使用相同的方法更新视图(触发器),但不使用数组,只使用对象。示例:$scope.obj=obj。它是有效的,问题只存在于对象数组上。
.factory('TestFactory', ['$rootScope', 'Auth', function ($rootScope, Auth) {
// ...
function addElement(index, value){
var obj = {}
obj.test=(value);
listObj[index].push(obj);
// notify the app that `addElement` has occurred
$rootScope.$broadcast('elementAdded');
};
// ...
}])
.controller('TestCtrl', function ($scope, $stateParams) {
var param1 = $stateParams.param1;
$scope.testList = TestFactory.getTest(param1);
// listen for elementAdded event; re-get testList
$scope.$on('elementAdded', function(){
$scope.testList = TestFactory.getTest(param1);
});
});