Error Detected by Directive Controller

My main focus is on utilizing the Directive Controller exclusively. Please respond to the error mentioned, as I believe that for each instance of directive usage, Angular will go through the controller section specified in the Directive.

// declaration of module 
var app = angular.module('myApp',[]);

// declaration of controller
app.controller('myCtrl',function($scope){
$scope.name = "Peter";
});

// declaration of app
app.directive('myStudent',function(){
return{
template: "Hi! Dear!! {{name}}<br/>",
controller:function(scope, elem, attr){
console.log("controller");
}
}
});
<body ng-app="myApp" ng-controller="myCtrl"> 

<my-student></my-student> 
<my-student></my-student> 
<my-student></my-student> 
<my-student></my-student> 
<my-student></my-student> 

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body> 

Note:

Please provide insights on the error and usage of the directive controller only. I am aware that the same can be achieved using pre-link, post-link, or compile functions.

PS: I find it puzzling why some alien genius decided to downvote this!

Answer №1

Instead of using a controller, I believe it would be more appropriate to utilize the link function.

//module declaration 
var app = angular.module('myApp', []);

//controller declaration
app.controller('myCtrl', function($scope) {
  $scope.name = "Peter";
});

//app declaration
app.directive('myStudent', function() {
  return {
    template: "Hi! Dear!! {{name}}<br/>",
    link: function(scope, elem, attr) {
      console.log("controller");
    }
  }
});
<body ng-app="myApp" ng-controller="myCtrl">

  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Controller accepts an array:

var app = angular.module('myApp', []);

//controller declaration
app.controller('myCtrl', function($scope) {
  $scope.name = "Peter";
});

//app declaration
app.directive('myStudent', function() {
  return {
    template: "Hi! Dear!! {{name}}<br/>",
    controller: [
      function(scope, elem, attr) {
        console.log("controller");
      }
    ]
  }
});
<body ng-app="myApp" ng-controller="myCtrl">

  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>
  <my-student></my-student>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
</body>

For more information, check out the angular documentation on directives

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

JavaScript: Learn how to simultaneously open two links from the current webpage

I am trying to create a browser bookmark that will open a link with the id: window.getElementById('updateOk').click() followed by opening a small window with another button: document.getElementsByClassName('rmit-save-details btn btn-inlin ...

Managing errors through middleware functions

Currently, I've been studying node.js on and off. I came across this question: Middleware 1: app.use(function(req, res, next) { db.load(function(err, session) { if (err) { return next(err); } ... }); }); Middleware 2: app.u ...

Setting the default TAB in a specific Menu Tab within the Menu Bar

I'm encountering some issues with this code. Specifically, the menu bar JavaScript is automatically clicking on the Second TAB instead of the First TAB when run. JS CODE. var dolphintabs = { subcontainers: [], last_accessed_tab: null, ...

Ideas for showing backslashes in the context of a Cognito filter solution

I need to apply a filtering on Cognito, and the required string format is as follows: "family_name = \"Reddy\"" Currently, I am using `email = "\"${email}"\"` However, when I check the console l ...

Restrict Angular 2 Component to specific ancestor Component

Is it possible in Angular 2 to restrict a Component so that it can only appear within a specific parent element on a page? In other words, the Component should only be allowed if it has a certain parent element. Here is an example: Allowed: <parent> ...

An issue in Node.js NPM PDFkit arises when generating PDF tables with Voilab pdf table, leading to paragraph errors in the resulting

Greetings everyone, I appreciate you taking the time to visit. I am currently facing some challenges with Voilab PDF Kit, a library for PDFkit that is designed to assist in organizing tables for NPM Pdfkit. After successfully generating a table, I attemp ...

JQuery failing to trigger AJAX function

I'm struggling with what seems like a simple issue and it's driving me crazy. The problem lies in this straightforward section of the website. I have a .js file that uses ajax to save a post into the database when the submit button is clicked. A ...

Updating data in a SQL database using PHP when a button is clicked

This Question was created to address a previous issue where I had multiple questions instead of focusing on one specific question Objective When the user selects three variables to access data, they should be able to click a button to modify one aspect o ...

Guide to showcasing images dynamically within a table

I am currently working on a dynamic table that updates its data using a script. My goal is to also display corresponding images of the groups next to their names in the table. Whenever the group names change, I want the images to change as well. The funct ...

Incorporating an SVG file within an img tag

In my ASP.NET mvc4 application, I have stored .svg files in the /content/Images folder. I am facing an issue while trying to use a .svg file as the src attribute under the <img> tag. It doesn't seem to work, even though inline svg works fine. H ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

After the ajax function has finished executing, establish a socket.io connection

Within my application, the initial step involves the client calling a webservice from a nodejs server to fetch historical data from a mongoDB database for visualization using the highcharts library. Subsequently, I need to receive live updates from the ser ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Exploring Angular's ngFor feature in building a dynamic accordion menu that automatically closes one panel and opens another when clicked

The Angular Material accordion component is a key feature in my Angular project. Utilizing an ngFor loop to iterate through the information stored in menuItems, I dynamically create a new expansion panel for each item. With two components in play, I seaml ...

What is the significance of providing a sole argument to the Object () function?

Answering a related question about object constructors, what is the intention behind passing an argument to the constructor of objects and using it in this specific manner? function makeFoo(a, b) { var foo = Object.create(Foo.prototype); var res ...

Tips for efficiently rendering over 200 views in React Native without sacrificing performance

I've been working on a game project using react-native and I'm facing an issue with rendering over 200 views on the Game screen. Each view should have a pressable functionality that, when pressed, will change the background color of the view and ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

React Native - Issue with array value not reflecting in Text component

import React, {useState} from 'react'; import { FlatList, Text, View} from 'react-native'; import {styles, styleBox} from './components/styles'; import Slider from '@react-native-community/slider'; export default fu ...

Display a Bootstrap input button group addon, where the first button has rounded corners only after the second button has been hidden

I am working on a button group and need to hide the second button dynamically. However, I am facing an issue where the first button has a 90° border. How can I adjust the code below to display button 1 with a rounded border? If I decide to hide "button ...

What is the best way to combine two arrays into a single array using AngularJS?

Here is a code snippet: $scope.studentDetails=[]; $scope.studentDetails=[0][id:101,name:one] [1][id:102,name:two] [2][id:103,name:three] $scope.studentMarks=[]; $scope.studentMarks=[0][id:101,marks:78] ...