2014-10-07 58 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/