您無法綁定變量。但是你可以綁定變量訪問器或者包含這個變量的對象。這裏是固定的jsfiddle。
基本上你必須傳遞一定範圍的東西,它可以返回/或保存當前值。例如。
廠:
app.factory('testFactory', function(){
var countF = 1;
return {
getCount : function() {
return countF; //we need some way to access actual variable value
},
incrementCount:function(){
countF++;
return countF;
}
}
});
控制器:
function FactoryCtrl($scope, testService, testFactory)
{
$scope.countFactory = testFactory.getCount; //passing getter to the view
$scope.clickF = function() {
$scope.countF = testFactory.incrementCount();
};
}
查看:
<div ng-controller="FactoryCtrl">
<!-- this is now updated, note how count factory is called -->
<p> This is my countFactory variable : {{countFactory()}}</p>
<p> This is my updated after click variable : {{countF}}</p>
<button ng-click="clickF()" >Factory ++ </button>
</div>
所以基本上,工廠僅僅是所述數據的數據和功能的共享(singleton)的容器中。你手動管理/同步數據進出$範圍? – sambomartin
@sambomartin正確。好文章[here](http://fdietz.github.io/recipes-with-angular-js/controllers/sharing-code-between-controllers-using-services.html) – user4815162342
所以通過傳遞函數testFactory.getCount而不是調用它,並在UI中調用它來綁定服務值。而如果你使用$ scope.countFactory = testFactory.getCount(),你只需要在初始化時調用一次函數,而沒有任何限制?所以如果價值改變,以後不更新? – mtpultz