2014-03-24 2 views
0

범위 A의 변수 중 일부를 변경하는 서비스를 사용하고 있습니다. 변수에 대한 변경 내용이 $watch 인 경우 아무 일도 일어나지 않습니다.

기본 설정은 아래와 같습니다. 요소에 추가하는 사용자 지정 지시문에 $watch을 사용하고 싶습니다. 하지만 불가능하다면 적어도 컨트롤러 내부에서 $watch을 사용할 수 있기를 바랍니다.

나는 plunkr here을 만들었습니다. $scope.someVar에서 볼 수 있듯이 $ watch는 컨트롤러 나 명령문에서 결코 실행되지 않습니다.

app.factory("changerService", function() { 
    var $scope; 
    function change(to) { 
    $scope.someVar = to; 
    } 
    function setScope(scope) { 
    $scope = scope; 
    } 
    return { 
    Change: change, 
    SetScope: setScope 
    } 
}); 

app.controller("bar", ["$scope", "changerService", function ($scope, changerService) { 
    $scope.someVar = true; 
    changerService.SetScope($scope); 
    $scope.showImg = function (val) { 
     changerService.Change(val); 
     $scope.state = $scope.someVar; 
    }; 

    $scope.$watch($scope.someVar, function (newVal, oldVal) { 
     $scope.watchController = newVal ? newVal : "undefined"; 
    }); 
}]); 

app.directive("myDirective", function() { 
    return { 
     link: function (scope, element, attrs) { 
      scope.$watch(scope.someVar, function (newVal, oldVal) { 
       scope.watchDirective = newVal ? newVal : "undefined"; 
      }); 
     } 
    } 
}); 

답변

1

enter image description here

코드를 검사 한 후 나는 시계식이 객체이지만은 문자열이어야합니다 것으로 나타났습니다.

예 :

app.controller("bar", ["$scope", "changerService", function ($scope, changerService) { 
    $scope.someVar = true; 
    changerService.SetScope($scope); 
    $scope.showImg = function (val) { 
     changerService.Change(val); 
     $scope.state = $scope.someVar; 
    }; 

    $scope.$watch("someVar", function (newVal, oldVal) { 
     $scope.watchController = newVal ? newVal : "undefined"; 
    }); 
}]); 

app.directive("myDirective", function() { 
    return { 
     link: function (scope, element, attrs) { 
      scope.$watch("someVar", function (newVal, oldVal) { 
       scope.watchDirective = newVal ? newVal : "undefined"; 
      }); 
     } 
    } 
}); 
+1

완벽하게! 감사 – user1873073

관련 문제