0

The following code works as expected and the scope.checked value is reflected in the UI normally

.directive('comparisonSlider',
    function () {
        return{
            restrict: 'E',
            templateUrl: '/app/reports/comparison-slider.html',
            controller: function ($scope, $rootScope) {
                $scope.checked = false;
                $rootScope.$on('compare',
                        function () {
                            $scope.checked = true;
                        },
                        true);
            }
        }
    }
)

but the following code also works, but the changes to scope aren't reflected in the UI.

.directive('comparisonSlider',
    function () {
        return{
            restrict: 'E',
            templateUrl: '/app/reports/comparison-slider.html',
            controller: function ($scope, $rootScope) {
                $scope.checked = false;
                $rootScope.$on('compare',
                        function () {
                            $scope.checked = !$scope.checked;
                        },
                        true);
            }
        }
    }
)

Any ideas?

Rod Johnson
  • 2,387
  • 6
  • 30
  • 48
  • Try $log.info($scope.checked) in function. You may need to inject $log service – shyammakwana.me Aug 07 '16 at 20:25
  • you haven't provided a lot of info to go on, but `$scope.checked` creates `checked` as a primitive property on `$scope`, which is subject to JavaScript Inheritance issues. This includes problems with using inside `ng-repeat`, `ng-include`, `ng-if`, or other similar directives, which means the problem may be in your HTML. If `checked` was an object, or in the case of your answer, a property on an object (the controller), then it's not subject to Inheritance problems. See http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – Claies Aug 07 '16 at 21:16

2 Answers2

0

This works as expected, not sure why the other one doesn't

.directive('comparisonSlider',
    function () {
        return{
            restrict: 'E',
            templateUrl: '/app/reports/comparison-slider.html',
            controllerAs: 'sliderCtrl',
            controller: function ($scope, $rootScope) {
                var self = this;
                self.checked = false;
                $rootScope.$on('compare',
                        function () {
                            self.checked = !self.checked;
                        },
                        true);
            }
        }
    }
)
Rod Johnson
  • 2,387
  • 6
  • 30
  • 48
0

Try changing:

self.checked = !self.checked;  

to:

self.checked = false;
developer033
  • 24,267
  • 8
  • 82
  • 108
techwestcoastsfosea
  • 686
  • 3
  • 10
  • 21