我在控制器内部创建了一个名为Call的工厂,我在$ scope内部有一个Call数组。我要做的是更新Call对象并更新$ scope。我已经尝试过使用$,但我无法让它工作,即使我能用它也有点麻烦......
如何在修改工厂对象时更新$ scope?
var ctiApp = angular.module('ctiApp', []);
ctiApp.controller('PhoneController', function($scope,$interval,$http,Call,$rootScope){
$scope.calls = [
];
$scope.dial = function(number){
var call = new Call();
call.dial(number);
$scope.calls.push(call);
}
});
// Factory
ctiApp.factory('Call',['$rootScope','$http', function($rootScope ,$http){
var Call = function() {
this.channel='';
this.uid='';
this.time='00:00:00';
this.state='connecting';
this.callerid='';
}
Call.prototype.dial = function(number){
$http({method: 'GET', url: '/url'}).
success(function(data, status, headers, config) {
if(data.data.response==='Success'){
console.log('#CONNECTED');
this.state = 'connected';
this.time = '00:00:00';
this.uid = data.data.uniqueid;
this.channel = data.data.channel;
this.callerid = number;
}
});
}
return Call;
}]);
注意:我已经从这些功能中删除了大部分功能,这就是为什么还有一些$ http,$ interval等等仍然落后......
答案 0 :(得分:1)
我知道这不是你的问题,但另一种方法是创建一个类的多个实例(例如你的Call类)就是使用$ controller服务。 Writing a Massive Angular App at Google NG Conf 演讲中推荐了这种方法。
以下是一个例子:
HTML:
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
instance1: {{ctrl.instance1}}
instance2: {{ctrl.instance2}}
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('Foo', function() {
var Foo = function($log) {
this.$log = $log;
this.sampleField = 1;
}
Foo.prototype.increaseSampleField = function() {
this.sampleField++;
this.$log.info('sample field is now: ' + this.sampleField);
};
return Foo;
}());
var myCtrl = function($controller) {
this.instance1 = $controller('Foo');
this.instance2 = $controller('Foo');
this.instance2.increaseSampleField();
}
这是JsFiddle:http://jsfiddle.net/robianmcd/M2Phe/
答案 1 :(得分:0)
解决方案实际上比在表面上看起来要简单得多。我最初更新错了,并且不需要使用像服务($ emit,$ broadcast,$ on等)这样的触发器来传播更改。
该功能最初不起作用的原因是因为这个原因。不再引用Call对象,而是引用它使用的$ http动词。
所以修改函数看起来像这样:
Call.prototype.dial = function(number){
var self=this;//This is key!
$http({method: 'GET', url: '/url'}).
success(function(data, status, headers, config) {
if(data.data.response==='Success'){
console.log('#CONNECTED');
self.state = 'connected';
self.time = '00:00:00';
self.uid = data.data.uniqueid;
self.channel = data.data.channel;
self.callerid = number;
}
});
}
答案 2 :(得分:0)
声明工厂的正确方法是返回一个函数示例:
app.factory('testFactory', function(){
return {
sayHello: function(text){
return "Factory says \"Hello " + text + "\"";
},
sayGoodbye: function(text){
return "Factory says \"Goodbye " + text + "\"";
}
}
});