2014-10-07 63 views
0

這裏有一個服務:設置與工廠獲得價值,angularJS

myApp.factory('myService', function() { 
    var test = 5; 

    return{ 
     setTestVal: function(val){ 
     test = val; 
     }, 
     getTestVal: function(){ 
     return test;  
     } 
    }  
}); 

這是我的控制器。其中獲得的價值和一個將其設置

function MyCtrl($scope, myService) { 
    $scope.test = myService.getTestVal(); 
} 

function SetCtrl($scope, myService){ 
    $scope.newTestVal = ''; 
    $scope.setTestVal = function(val){ 
     myService.setTestVal(val) 
    } 
} 

但沒有更新的觀點時,我設置的值。

小提琴:http://jsfiddle.net/HB7LU/7036/

這是錯誤的做法,以設置和獲取價值?

回答

1

沒有,這種做法是完全正常的,但認爲有當一個新的值設置不知道,你要設置的共享屬性$watch

$scope.$watch(function() { 
    return myService.getTestVal(); 
}, function(value) { 
    $scope.test = value; 
}); 

小提琴:http://jsfiddle.net/HB7LU/7041/

+0

猜猜我正在用雙向數據綁定變壞。謝謝。 – Per 2014-10-07 21:18:27

0

你甚至可以做到這一點,而不$手錶, 檢查撥弄我從你的修改:

var myApp = angular.module('myApp',[]); 
myApp.factory('myService', function() { 
    var test = 5; 
    var obj = { 
     test : 5 
    } 

    return{ 
     setTestVal: function(val){ 
     test = val; 
     obj.test = val; 
     }, 
     getTestVal: function(){ 
     return test;  
     }, 
     data : obj 
    } 


}); 

function MyCtrl($scope, myService) { 
    $scope.test = myService.getTestVal(); 
    $scope.data = myService.data; 
} 

function SetCtrl($scope, myService){ 
    $scope.newTestVal = ''; 
    $scope.setTestVal = function(val){ 
     myService.setTestVal(val) 
    } 
} 

http://jsfiddle.net/no9rv2nb/