2014-02-26 71 views
0

我已經在控制器內部創建了一個名爲Call的工廠我在$ scope中有一個Calls數組。我想要做的是更新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,$間隔等,仍落後....

回答

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; 
      } 
     }); 
} 
0

宣佈工廠將返回有道功能例如:

app.factory('testFactory', function(){ 
return { 
    sayHello: function(text){ 
     return "Factory says \"Hello " + text + "\""; 
    }, 
    sayGoodbye: function(text){ 
     return "Factory says \"Goodbye " + text + "\""; 
    } 
}    
}); 
+0

這就是我最初使用,但返回一個類而不是更容易。使用新關鍵字時未遇到問題。 – Mattisdada

1

我知道這是不是真正的問題,你有,但另一種方式創建一個類的多個實例(例如,您的電話類)是使用$控制器服務。這個方法在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/