2014-01-30 3 views
0

다른 컨트롤러에서 여러 번 사용할 수있는 컨트롤러 용 재사용 가능한 구성 요소를 만들려고합니다.각도 컨트롤러의 재사용 가능한 구성 요소

참조 plunker : http://plnkr.co/edit/Lc4z4L?p=preview

plunker에 표시된 문제는, 그는 FirstCtrl에서 같은 메시지가 SecondCtrl에 비해 표시됩니다된다.

서비스와 관련하여 분리 된 범위를 달성하려면 어떻게해야합니까? 아니면 잘못된 개념을 사용하고 있습니까?

app.service('alertService', function($timeout) { 
    return function() { 
    // assign this to service only because I'm lazy 
    var service = this; 
    var timeout; 

    // start with empty array holding the alerts. 
    service.alert_list = []; 

    // method to add an alert 
    // alert_obj is a object with members type = (success | info | warning | danger) 
    // and msg which is the message string 
    service.addAlert = function (alert_obj) { 
     service.alert_list = []; 
     service.alert_list.push(alert_obj); 
     $timeout.cancel(timeout); 
     timeout = $timeout(service.clearAlerts, 5000); 
    }; 

    service.clearAlerts = function clearAlerts() { 
     service.alert_list = []; 
    }; 
    } 
}); 

업데이트 된 컨트롤러 :이 서비스는 하나의 인스턴스를 가지고 사실이지만

+1

읽기 : // 할 cs.angularjs.org/guide/dev_guide.services.creating_services). 앱 전체에 걸쳐 하나의 서비스 인스턴스 만 보유하고 있습니다. (페이지 ctrl + f : 싱글 톤 서비스) – Dieterg

+0

@DieterGoetelen 감사합니다! 나는 그것을 읽고 나는이 문제를 해결하는 데 사용할 수있는 각도 개념을 찾고있다. – Thomas

+0

지시어에 다른 객체를 전달하기 만하면됩니다. 동일한 객체를 사용하고 있습니다 => 동일하게 표시됩니다. –

답변

2

, 당신은 또한 당신이 다음 new 컨트롤러에서 당신에게 그 함수의 개별 인스턴스를 줄 것이다 할 수있는 기능을 반환 할 수 있습니다 지금과 같을 것이다 :

app.controller('SecondCtrl', function($scope, alertService, $timeout) { 

    $scope.alertService = new alertService(); 

    $scope.alertService.addAlert({"type": "info", "msg": "Infomessage II"}); 

    $scope.name = 'World II'; 
}); 

업데이트 plunker : [AngularJS와 워드 프로세서 (HTTP에서 서비스에 대한 http://plnkr.co/edit/RhJbbxj4XxdwY6GAest9?p=preview

관련 문제