How are these two Controllers connected?

Currently immersed in an AngularJS book and feeling perplexed by something

There are two Controllers that have caught my attention

EditCtrl

app.controller('EditCtrl', ['$scope', '$location', 'recipe', 
function($scope, $location, recipe){
    $scope.recipe = recipe;

    $scope.save = function(){
        $scope.recipe.$save(function(recipe){
            $location.path('/view/', + recipe.id);
        });
    };

    $scope.remove = function(){
        delete $scope.recipe;
        $location.path("/");
    };
}]);

IngredientsCtrl

app.controller('IngredientsCtrl', ['$scope',
function($scope){
    $scope.addIngredients = function(){
        var ingredients = $scope.recipe.ingredients;
        ingredients[ingredients.length] = {};
    };

    $scope.removeIngredient = function(index) {
        $scope.recipe.ingredients.slice(index, 1);
    };
}]);

The part that's baffling me is the connection between IngredientsCtrl and EditCtrl. The relationship isn't clear to me. Even though the example app functions seamlessly as per the book, I need more insight into what exactly makes IngredientsCtrl linked as a child of EditCtrl. It's not clicking for me.

Edit: Including relevant HTML markup

<div class="control-group">
<label class="control-label" for="ingredients">Ingredients:</label>
<div class="controls">
  <ul id="ingredients" class="unstyled" ng-controller="IngredientsCtrl">
    <li ng-repeat="ingredient in recipe.ingredients">
      <input ng-model="ingredient.amount" class="input-mini">
      <input ng-model="ingredient.amountUnits" class="input-small">
      <input ng-model="ingredient.ingredientName">
      <button type="button" class="btn btn-mini" ng-click="removeIngredient($index)"><i class="icon-minus-sign"></i> Delete </button>
    </li>
    <button type="button" class="btn btn-mini" ng-click="addIngredient()"><i class="icon-plus-sign"></i> Add </button>
  </ul>
</div>

Edit: Excerpt from the book

All previously encountered controllers were associated with specific UI views, but the Ingredients Controller stands apart. As a child controller utilized on edit pages, it encapsulates particular functionalities unnecessary at a broader level. An intriguing aspect is that being a child controller lets it inherit the scope from the parent controller (in this situation, the Edit/New controllers). Hence, it gains access to the $scope.recipe from its parent.

Edit: Integration with routing

var app = angular.module('guthub', 
      ['guthub.directives', 'guthub.services']);

app.config(['$routeProvider', 
    function($routeProvider){
        $routeProvider.
         when('/', {
             controller: 'ListCtrl', 
             resolve: {
                 recipes: function(MultipleRecipeLoader){
                     return MultipleRecipeLoader();
                 }
             },
             templateUrl: '/view/list.html'
         }).
         when('/edit/:recipeId', {
             controller: 'EditCtrl',
             resolve: {
                 recipe: function(RecipeLoader) {
                     return RecipeLoader();
                 }
             },
             templateUrl: '/view/recipeForm.html'
         }).
         when('/view/:recipeId', {
             controller: 'ViewCtrl',
             resolve: {
                 recipe: function(RecipeLoader) {
                     return RecipeLoader();
                 }
             },
             templateUrl: '/view/viewRecipe.html'
         }).
         when('/new', {
             controller: 'NewCtrl',
             templateUrl: '/view/recipeForm.html'
         }).
         otherwise({redirectTo: '/'});
}]);

Answer №1

Controllers establish a Parent-Child relationship by placing the ng-controller directive on two nested HTML elements.

Upon reviewing your HTML template, you will likely observe something similar to the following:

<!-- parent controller -->
<div ng-controller="EditCtrl">
    <!-- child controller -->
    <div ng-controller="IngredientsCtrl"></div>
</div>

Answer №2

In angular, there is no concept of a child controller per se. However, you can nest controllers inside one another in the DOM structure.

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
        // By nesting controllers like this, you can access both scopes
    </div>
</div>

Regarding the relation between these two controllers, they are not inherently related. Nesting them is simply a structural choice and does not create any automatic connection.

It's worth noting that having both controllers read from the scope is generally considered poor practice, as advocated by Miško Hevery himself (http://www.youtube.com/watch?v=ZhfUv0spHCY).

To quote him:

Controllers should focus on write operations to the scope, while templates should be limited to read-only actions

Based on the code examples provided, I would advise caution when using the learning material that introduced these practices in angularjs.

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

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Contrasts between the AngularJS injector and NodeJS require module

I'm curious about the dependency injection concept in AngularJS and NodeJS. Is there a distinction between $injector in AngularJS and the require module in NodeJS? Could utilizing the require module be advantageous in a MEAN STACK setup as opposed t ...

When encountering error code EINTEGRITY during npm installation, a warning about a potentially corrupted tarball may be displayed

I have been facing an issue for the last three days with my react+vite project on Windows 10. Whenever I attempt to install dependencies using npm install, I encounter the following error: npm WARN tarball tarball data for fast-levenshtein@https://registry ...

Refreshing Information Iteratively

I am currently working on updating the rate field in the currency table using my nodejs controller. While everything runs smoothly in S3T / RoboMongo, I'm facing an issue where the update operation doesn't seem to execute inside the nodejs contr ...

angularjs - user-defined attribute turns blank

I'm having an issue when trying to unshift an object into an existing array list in AngularJS. After doing so, one of the values becomes empty. What is the correct way to add a new object to an existing array in AngularJS? Here's my code: var ...

The ngShow directive is being assessed prematurely

In my development project, I have an Angular component and controller set up in the following way: export class MyController{ static $inject = [MyService.serviceId]; public elements: Array<string>; public errorReceived : boolean; ...

Issue occurs when attempting to call a function from a button

I am in the process of creating a form to collect information from a group of individuals, and whenever I try to add another person by clicking on the button, an error message pops up in the console saying that addPerson() is not recognized as a function. ...

disable parent directive execution when child element is clicked

Here I have implemented a pop-over directive, and I want to apply it to both the parent and child elements. When I click on the child element, the parent directive is also displayed. How can I prevent event propagation to the parent element? Is it possible ...

Is there a way to incorporate animation while calculating a number?

I am looking to add some special animation effects to the number in this script, but I am not sure how to achieve that. $('#choose').change(function() { if($(this).val() == '1') { document.getElementById('harga&ap ...

Attaching a click event to an element located within the template of a directive

I decided to create a reusable directive in order to make a common component, but I am facing an issue trying to capture the click event of an element inside the template used within the directive. Take a look at the code snippet below for better understa ...

Having trouble displaying a list in HTML using ngFor syntax

I'm relatively new to angular and front-end development. I'm currently trying to make a call to a REST API in order to fetch a list of products, and then display them on the HTML page. product.component.html <div class="page-title"& ...

How can I automatically populate values in a series of dropdown menus using AngularJS?

Experiencing a challenge I am currently encountering an issue with the select functionality in Angular JS. This question is a continuation of my previous inquiry, where I was able to successfully load values into the second select dropdown but faced diffi ...

The AngularJS $http.post method mimicking a successful $.ajax request is causing a 401 UNAUTHORISED error

I have been working on rewriting a functional $.ajax server call to utilize AngularJS $http.put. However, the $http method returns a 401 unauthorized error. The original ajax call I am attempting to rewrite is structured like this: $.ajax({ url: domain ...

Clone a specific link within a div using jQuery only one time

I have a group of divs and I want to copy the link from the first div and put it into the last div (mobile-link). Currently, it is either duplicating all the links and inserting them all at once, or if I use :eq(0), it's placing the first link in each ...

Efficient method for sending a high volume of rows to AWS Lambda from datatables (approximately 10,000 rows)

Currently, I am working on an extension for Tableau that captures user decisions and saves them as rows in datatables using JavaScript. These modified rows are then sent to AWS Lambda in JSON format. In AWS Lambda, we process the data from these rows by ge ...

Attempting to transfer a Vue component from one component to another, without directly involving the App.vue file

Hello everyone, I recently created a component called Hamburger.vue in my components directory. I then attempted to import this hamburger component into my Header.vue file to avoid unnecessary code repetition. For reference, here is the link to the playg ...

Rebuild object methods obtained from localStorage

Utilizing JSON.stringify and JSON.parse to save and retrieve objects from localStorage has led to a discovery - JSON.stringify seems to remove the instance functions from the object. This means that once I use JSON.parse, I lose the ability to execute m ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

The default data value in the Vue component is taking precedence over the value I specified in beforeRouteUpdate

When navigating in my Vue application, I utilize vue-router's beforeRouteEnter and beforeRouteUpdate to retrieve data from a REST API. <template> <div> <h2>{{ league.name }} </h2> <user-list :users="league.leaderb ...

What would be more efficient for designing a webpage - static HTML or static DOM Javascript?

My burning question of the day is: which loads faster, a web page designed from static html like this: <html> <head> <title>Web page</title> </head> <body> <p>Hi community</p> </bo ...