2013-10-24 117 views
0
angular.module('app.services', []).service("test", function($http, $rootScope){ 
this.test=function(){ 
$rootScope.name="test1"; 
}; 
}; 

angular.module('app.controllers', []).controller('TestController', function ($scope, test) { 
       test.send();  
    }) 

我沒有得到一個錯誤,但這些更改沒有應用到UI。我試過$ scope.apply()並出現錯誤。從服務更新角度模型

回答

0

我們需要告訴Angular哪個模塊您的模塊依賴於在我們的情況下主模塊是app.controllers

撥叫,我們需要告訴控制器不同型號的服務哪裏是我們的服務宗旨:

['app.services'] 

JS

var appServices = angular.module('app.services', []); 
var appCtrl = angular.module('app.controllers', ['app.services']); 

appServices 
.service("test", function ($http, $rootScope) { 
    this.send = function() { 
     $rootScope.name = "test1";  
    }; 
}); 

appCtrl.controller('TestController', function ($scope, test) { 
    test.send(); 
}); 

演示Fiddle

+0

感謝還是調用$ rootScope.name = 「測試1」;不更新ui – nullException

+0

你有沒有看到我貼的小提琴?請發佈您的HTML代碼 –

0

我想你應該改變「.service」by「.factory」。

正如我可以在creating services docs看到有創建自定義服務的3種方式。其中之一是使用工廠方式,如下所示:

var myModule = angular.module('myModule', []); 
    myModule.factory('serviceId', function() { 
     var shinyNewServiceInstance; 
    //factory function body that constructs shinyNewServiceInstance 
    return shinyNewServiceInstance; 
    }); 

希望能提供幫助。