Creating an angular controller in a template based on certain conditions

When working with Angular.js, I'm attempting the following:

index.html

<div class="data-tabs-sms-scroll" ng-show="question.type == 'open'"
     ng-controller="AudioMessagesCtrl"
     ng-include="'/templates/audioMessages.html'"></div>
<div class="data-tabs-sms-scroll" ng-hide="question.type == 'open'"
     ng-controller="QuestionDetailCtrl"
     ng-include="'/templates/questionDetail.html'"></div>

app.js

ulizaApp.controller('AudioMessagesCtrl', ['$scope', 'QuestionResponse', 'ngAudio',
  function($scope, QuestionResponse, ngAudio) {
    console.log(
      'questionDetailCtrl', 
      $scope.$parent.question.id, 
      $scope.$parent.question.type
    );
  }]);

ulizaApp.controller('QuestionDetailCtrl', ['$scope', 'Question',
  function($scope, Question) {
    console.log(
      'questionDetailCtrl', 
      $scope.$parent.question.id, 
      $scope.$parent.question.type
    );
  }]);

Firefox console output

"questionDetailCtrl" 563 "multi" AudioMessagesCtrl.js:6:4
"questionDetailCtrl" 563 "multi" QuestionCtrl.js:6:4
"questionDetailCtrl" 564 "open" AudioMessagesCtrl.js:6:4
"questionDetailCtrl" 564 "open" QuestionCtrl.js:6:4

I want to ensure that the AudioMessagesCtrl is only instantiated when question.type is “open”, and the QuestionDetailCtrl is created whenever question type differs from open.

This approach doesn't seem to be working for me. Any suggestions?

Thank you!

Answer №1

When using ng-show/ng-hide, the dom is initially rendered and then a decision is made whether to show/hide based on the condition.

ng-if, on the other hand, only renders the dom if the condition is met.

Therefore, it's recommended to use ng-if instead of ng-show/ng-hide.

Code Example:

<div class="data-tabs-sms-scroll" ng-if="question.type == 'open'"
     ng-controller="AudioMessagesCtrl"
     ng-include="'/templates/audioMessages.html'"></div>
<div class="data-tabs-sms-scroll" ng-if="question.type == 'open'"
     ng-controller="QuestionDetailCtrl"
     ng-include="'/templates/questionDetail.html'"></div>

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

The jQuery script designed to verify the page height doesn't appear to be functioning as intended

Below is a snippet of jQuery code that I'm working with: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> hasVBar=""; hasHBar=""; $(docume ...

Navigate within a div using arrow keys to reposition another div

As a newcomer to JavaScript, I am facing some challenges. My goal is to use arrow keys to move a small div inside a larger div. However, the code below is not functioning as expected. Here is the HTML and CSS: <div id="rectangle"> <div id="s ...

Replacing child routes with an Angular wildcard route

I'm facing an issue with integrating a module named "host" into the app-routing.module. The problem I encountered is that the wildcard route takes precedence over loading the Host component, leading to the display of the PageNotFoundComponent instead. ...

Is there a way to detect browser errors using JavaScript or Angular 2?

On the back-end, I am looking to add these uncaught errors to the log file. These errors are not being captured in angular2. How can I go about reading and handling these errors?https://i.sstatic.net/Kljon.png ...

`Can't figure out how to input variables into PHP Form`

As a newcomer to PHP, I apologize if this question seems obvious. I would like to create a form that gathers more information than just the typical "name," "email," and "message." I am specifically looking to include the following labels: (i) Will you be ...

Having trouble with krakenjs angularjs $http's delete method not functioning as expected

While using KrakenJs, I came across a workaround to send POST/PUT/DELETE requests without disabling "csrf" by including a "_csrf" parameter in the body In my index.dust file: <input id="csrfid" type="hidden" name="_csrf" value="{_csrf}"> In myScri ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

When utilised within the same function, JSON values in JavaScript can yield varying results

Recently, I've been grappling with a JavaScript issue that involves fetching JSON values as data-attributes to populate a modal. This task sounds simple enough, but as a newcomer to this field, I find myself facing challenges. The main goal is to ite ...

A guide on implementing Google reCAPTCHA in a Nuxt.js website

Trying to implement the recaptcha-module from nuxt-community in my Nuxt project but struggling with verifying if the user has passed the check. The documentation and example provided are not clear enough for me (https://github.com/nuxt-community/recaptch ...

There is an error in the TypeScript code where it is not possible to assign a string or

I'm struggling to resolve a typescript error. Upon checking the console log, I noticed that the regions returned by Set are an array of strings, which aligns perfectly with the region type in my state. Why isn't this setup working as expected? S ...

How to center items within a Toolbar using React's material-ui

I need help with implementing a toolbar on a page that contains three ToolbarGroup components: <Toolbar> <ToolbarGroup firstChild={true} float="left"> {prevButton} </ToolbarGro ...

Guide to exporting specific files in Node.js or Deno

Utilizing the export keyword in JavaScript allows us to export any content from one file to another. Is there a way to restrict exports to specific files, preventing other files from importing them? export const t = { a: 'this will only be exported fo ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Combining the powers of Javascript and Drupal can create

My current setup includes an "open video" button and a form that triggers an ajax call to render files with the corresponding buttons when users click on handouts or videos. I have encountered a problem: Whenever I click on "open the video" after renderi ...

Advantages of passing individual variables instead of the entire object from HTML to JavaScript in AngularJS

When it comes to passing the iterating object from HTML to Javascript, there are two approaches that can be taken. The first approach involves passing the iterating object as a whole, while the second approach only passes the required properties of the obj ...

Is it necessary to insert a thread sleep in HtmlUnit before clicking a button?

I have been experimenting with HtmlUnit to extract scores from the BBC Sports website Upon loading the page, it initially displays Premier League scores. To view scores for other leagues, one must use a dropdown menu and click the 'Update' butto ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

How to Extract a URL from an Anchor Tag without an HREF Attribute Using Selenium

How can I make a link, which normally opens in a new window when clicked, open in the current window instead? The link does not have an href attribute, only an id and a class. For example: <a id="thisLink" class="linkOut">someLinkText</a> I r ...