runners3431 runners3431 - 1 month ago 7
Javascript Question

Why doesn't my scope show with a directive?

I'm creating a directive with a custom controller and testing out the scope. I want to test if the directive has a scope from my index page but the ng-show is not working.

html

<div class="main">
<div ng-controller="rl">

<book-genres></book-genres>
<review-form ng-show="reviewFormCtrl.rating == 1"></review-form>
<input ng-click="reviewFormCtrl.rating = 3" type="button" value="Test" />

</div>

</div>


partial:

<div>
Review Forms : {{ rating }}

</div>


controller:

myApp.controller('rl', function(){

});

myApp.directive('reviewForm', function(){
return {
restrict: 'E',
templateUrl: 'partials/review-form.html',
replace: true,
scope: true,
controller: function($scope){
$scope.rating = 1;
},
controllerAs: 'reviewFormCtrl'
};
});

Answer

Because you are using the controller as syntax (e.g. controllerAs: 'reviewFormCtrl'), you should attach rating to the controller instead of scope.

This should work

myApp.directive('reviewForm',  function(){
  return {
    restrict: 'E',
    templateUrl: 'partials/review-form.html',
    replace: true,
    scope: true,
    controller: function(){
      this.rating = 1;  //change here
    },
    controllerAs: 'reviewFormCtrl'
  };
});