正確的,你是在正確的方向,看看這都是我爲你創建的,在我的範圍變量,它提供了訪問服務變量增值服務的Plunkr。服務內部的對象將很容易在視圖中訪問。
HTML
<div ng-controller="Ctrl1" style="float: left">
Upper Section
<div ng-repeat="i in [1,2,3,4,5]" ng-class="{green: dataService.data.selected == i, red: dataService.data.selected != i}"
ng-click="dataService.data.selected = i" ">{{i}}</div>
{{dataService}}
<div>
<div ng-controller="Ctrl2 " style="float: right ">
Bottom Section
<div ng-repeat="i in [1,2,3,4,5] " ng-class="{green: dataService.data.selected==i , red: dataService.data.selected !=i } "
ng-click="dataService.data.selected=i ">{{i}}</div>
{{dataService}}
<div>
代碼
angular.module('app',[])
.controller('Ctrl1', function($scope, dataService){
$scope.dataService = dataService;
})
.controller('Ctrl1', function($scope,dataService){
$scope.dataService = dataService;
}).
service('dataService', function(){
this.data = {};
this.getData = function(){
return this.data;
};
this.setData = function(val){
this.data = val;
};
});
Working Plunkr
我敢肯定,這是正確的做法。如果您定義了一個剛剛插入服務/工廠當前值的指令,那麼DOM綁定會更直接。 – 2015-04-03 11:19:35
這是正確的做法。你不應該直接綁定服務來查看。它應該通過控制器。而作爲需要對數據進行多個控制器之間共享,那麼服務是最好的地方 – mohamedrias 2015-04-03 11:23:03