What could be causing my directive to not display my scope?

I am currently developing a directive that includes a custom controller, and I am testing the scope functionality. However, I am facing an issue where the ng-show directive is not functioning as expected when trying to test if the directive has a scope from my index page.

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 №1

Since you are utilizing the controller as syntax (for example, controllerAs: 'reviewFormCtrl'), it's recommended to attach the rating to the controller rather than the scope.

Here is the modified code:

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'
  };
});

Answer №2

Following @Dustin Hodges' advice, here is a more organized approach:

Directive:

angular
 .module('myApp')
 .directive('reviewForm',  function(){

  var directive = {
      restrict    : 'E',
      templateUrl : 'partials/review-form.html',
      replace     : true,
      scope       : true,
      controller  : 'ReviewFormController'
      controllerAs: 'reviewformCtrl'
  };

 return directive;

});

Controller:

angular
  .module('myApp')
  .controller('ReviewFormController', ReviewFormController);

  ReviewFormController.$inject = [];//your dependencies

  function ReviewFormController(){

    var vm = this;

    vm.rating = 1;

  }

Template:

<div class="main">
 <book-genres></book-genres>
  <review-form ng-show="reviewformCtrl.rating == 1"></review-form>
</div>

I hope you find this cleaner format helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

The issue arises when attempting to update the input of a child component within a reactive form during the OnInit lifecycle

My dilemma arises in working with data stored in the ngrx entity store, as it gets displayed in chunks based on pagination. The issue lies with rxjs somehow remembering the paging history. For instance, when I fetch the first page of data from the server, ...

Stream-Awesome #12: The Return of Duplexer in Nodesville

For days, I've been attempting different methods to solve this exercise. It's frustrating because no matter what I try, I keep encountering a "write after end" error. But here's the thing - I'm using the "end" event and not writing anyt ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

Implementing mouse hover functionality in a VueJS component within a Laravel application

I am facing an issue with my mouse hover functionality while working on Laravel. The Vue file I am using is located in resources/js/Dashboard.vue I have attempted to replace v-on:mouseover with @mouseover but the problem persists. When I hover over the ...

Exploring JQuery Mobile: A guide on looping through elements in a list and collecting their unique identifiers

I am facing a challenge with a list of li tags within an unordered list. Each tag is assigned a class=listitem and a data-clicked=true/false. My task is to extract only the id's of those with data-clicked=true, add them to a string named custidlist, a ...

In Typescript, if at least one element in an array is not empty, the function should return false without utilizing iterators

My current approach involves receiving a string array and returning false if any of the elements in the array is false. myMethod(attrs: Array<String>) { for (const element of attrs) { if (!element) { return false; } } ...

Dealing with Content-Range for pagination in Restangular: A comprehensive guide

When working with an API that returns the header "Content-range" for lists, how can I efficiently retrieve and parse this header value using Restangular? Do I need to create a custom function for this task? Is there an existing method in Restangular that ...

The functionality of Vue is acting up with the HTML, unexpectedly refreshing when a button is clicked

I am currently experiencing an issue with my Vue application. When I click the button, it clears the input field (which it shouldn't) and doesn't perform any other actions. The variables "codigo" and "payload" do not display anything on the scree ...

New navigation menu changes as user scrolls

I'm struggling to find a way to implement a different navigation menu that appears when the user scrolls down. I'm envisioning something similar to this example: My goal is to have #small-menu replace #big-menu once the user starts scrolling. C ...

Embed an angular directive into HTML dynamically

I have a multitude of directives within my angular module, ranging from MyDirective1 to MyDirectiveN. Furthermore, I keep track of these directive names in MyDirectiveList: ['MyDirective1', 'MyDirective2', ..., 'MyDirectiveN' ...

user input not displayed within md-autocomplete

I'm currently incorporating angular material's autocomplete component into my website. Within the html code, I have the following: <md-autocomplete md-selected-item="selectedItem" md-search-text="searchText" md-items="item in getMatches ...

How do I determine when an attribute's expression in AngularJS Directive has been completely evaluated?

Suppose there is a directive that takes in an attribute called "url" which can consist of expressions and static texts. The evaluated result of this "url" attribute will be used as the URL in an ng-include within the directive's template. How can I ve ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

Deleting items from an array in ReactJS

When retrieving a list of users from AWS Cognito, everything works flawlessly. However, the task of iterating over this array and removing users that do not match a specific Client ID is where I'm facing difficulties. What am I doing wrong in this sc ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

Utilizing Radio buttons for validation in react-hook-form

After creating a form with radio buttons and implementing validation using React Hook Form, I encountered an issue where the console always displayed "on" regardless of the selected radio button. <div className=""> <label ...

What is the best way to select the enclosed <a> tag within an <li> element?

Below is the JavaScript code I have attempted: $('#footer').find('.browse li').click(function(e){ $(this).find('a').click(); }); Here is the relevant HTML: <div id="footer" class="span-24"><div ...

JavaScript's replace() method and the $1 issue

My goal is to develop a script that can identify specific patterns within text and then enclose them in particular tags upon identification. $(".shop_attributes td").each(function () { $(this).html(function(i, html) { return html.replace(/E[0- ...

Using AngularJS routing with an Express 4.0 backend API

Recently, I began working on an application utilizing Express 4.0 server. Following a tutorial on scotch.io (http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4), I structured the routes to support a backend api serving an An ...