2014-11-24 2 views
1

나는 angularjs를 사용하기 시작했으며, 내가 본 첫 번째 예제는 $scope 대신 this을 사용하는 예제입니다. 예를

app.controller('TabController',function(){ 
    this.tab = 1; 
}); 

에 대한

나는 컨트롤러간에 데이터를 전달하기 위해 노력하고 있습니다. 내가 본 모든 예제는 $rootScope을 사용하는 서비스를 사용하고 이벤트를 브로드 캐스트합니다. 그런 다음 컨트롤러는 $scope.$on을 사용하여 해당 이벤트를 수신합니다.

예를

app.service('mySharedService', function($rootScope) { 
    var sharedService = {}; 

    sharedService.tab = 1;  

    sharedService.setTab= function(tab) { 
     this.tab = tab; 
     $rootScope.$broadcast('handleBroadcast'); 
    }; 

    return sharedService; 
}); 

app.controller('TabController',['$scope','mySharedService',function($scope,mySharedService){ 
    $scope.tab = 1; 
    $scope.$on('handleBroadcast', function() { 
     $scope.tab = sharedService.tab; 
    }); 
}]); 

에 대한 내 질문에 내가 $scope를 사용하는 대신 this을 사용하지 않고이 작업을 수행 할 방법이다. 여기 당신은 컨트롤러 내부에 서비스를 주입하고 소비한다 전체 plunk

+1

입니다

app = angular.module('app', []); app.service('SharedService',function(){ this.counter = {value:0}; this.add = function (amount){ this.counter.value++;} }); app.controller('TabController',['SharedService',function(SharedService){ this.sharedService = SharedService; this.counter = SharedService.counter; this.add = function(amount){ this.sharedService.add(amount); } }]); 

: –

+1

http://plnkr.co/edit/xtaDF5FQtz99dbl1ZI3x?p=preview 내가 당신을 위해 설정 한이 plunk를보십시오. – Dieterg

+0

이것을 사용해도 $ scope, $ rootScope 또는 둘 다를 사용할 수 있습니다. –

답변

0

나는 @Dieter Goetelen 응답을했고 그것을 조금

결과

을 변경했습니다.
+1

다행 니가 해결책을 찾도록 도울 수있어. – Dieterg

관련 문제