2014-10-14 7 views
1

각도로 간단한 알림을 보내고 싶습니다. 여기에 제가 작성한 코드가 있습니다. http://pastebin.com/zYZtntu8 질문 : hasAlerts() 메소드에 새 경고를 추가하면 작동하지만 NoteController에 새 경고를 추가하는 이유는 무엇입니까? 나는 $ scope로 뭔가를 시도했지만 $ watch하지만 작동하지 않거나 잘못했다.AngularJS에서 다른 컨트롤러의 변수를 설정하는 방법은 무엇입니까?

어떻게하면됩니까?

+0

문제가 무엇인지, 작동하지 않는지 완전히 이해하지 못합니다. 문제를 드러내는 바이올린을 준비 할 수 있습니까? – Alexei

답변

2

체크 아웃 한 동안을 만들어이 plnkr 다시 http://plnkr.co/edit/ABQsAxz1bNi34ehmPRsF?p=preview

나는 처음 두가 시계없이 작업을 수행하는 방법을 보여 몇 가지 방법이 컨트롤러는 특히 서비스에서 데이터를 사용할 수 있습니다 보여 일반적으로 더 효율적인 방법은 이동 :

// Code goes here 

angular.module("myApp", []).service("MyService", function($q) { 
    var serviceDef = {}; 
    //It's important that you use an object or an array here a string or other 
    //primitive type can't be updated with angular.copy and changes to those 
    //primitives can't be watched. 
    serviceDef.someServiceData = { 
    label: 'aValue' 
    }; 
    serviceDef.doSomething = function() { 
    var deferred = $q.defer(); 

    angular.copy({ 
     label: 'an updated value' 
    }, serviceDef.someServiceData); 

    deferred.resolve(serviceDef.someServiceData); 
    return deferred.promise; 
    } 
    return serviceDef; 
}).controller("MyCtrl", function($scope, MyService) { 
    //Using a data object from the service that has it's properties updated async 
    $scope.sharedData = MyService.someServiceData; 
}).controller("MyCtrl2", function($scope, MyService) { 
    //Same as above just has a function to modify the value as well 
    $scope.sharedData = MyService.someServiceData; 
    $scope.updateValue = function() { 
    MyService.doSomething(); 
    } 
}).controller("MyCtrl3", function($scope, MyService) { 
    //Shows using a watch to see if the service data has changed during a digest 
    //if so updates the local scope 
    $scope.$watch(function(){ return MyService.someServiceData }, function(newVal){ 
    $scope.sharedData = newVal; 
    }) 
    $scope.updateValue = function() { 
    MyService.doSomething(); 
    } 
}).controller("MyCtrl4", function($scope, MyService) { 
    //This option relies on the promise returned from the service to update the local 
    //scope, also since the properties of the object are being updated not the object 
    //itself this still stays "in sync" with the other controllers and service since 
    //really they are all referring to the same object. 
    MyService.doSomething().then(function(newVal) { 
    $scope.sharedData = newVal; 
    }); 
}); 

것 같아요 여기서 주목할만한 것은 내가 그에게 새로운 객체 또는 배열을 할당하는 대신 서비스에서 만들어지는 동일한 개체를 다시 사용하는 angular.copy를 사용한다는 것입니다 재산. 컨트롤러에서 해당 객체를 참조하고 데이터 바인딩 상황 (보기에서 시계 또는 {{}} 보간)에서이 객체를 사용하면 객체에 대한 변경 사항이 표시됩니다.

+0

아마도 이것은 해결책입니다. 난 그냥 내 코드에 그것을 구현하려고합니다. 감사. – tdudzik

관련 문제