Retrieve the parameter value from a directive within a controller

Looking to implement a directive and utilize the argument in your controller?

<body ng-app="tstApp">
    <navigationbar tst="hello">
    </navigationbar>
</body>

To achieve this, you will need to create a directive along with its corresponding controller:

navigationBar = {};
navigationBar.directives = {};
navigationBar.controllers = {};

navigationBar.directives.navigationbar = function () {
    return {
        restrict: 'E',
        scope: {
            t1: '@tst',
            t2: '=tst',
            t3: '&tst'
        },
        templateUrl: "common/navigation_bar/navigation_bar.tpl.html",
        controller: "NavigationBarController"
    }
};

navigationBar.controllers.NavigationBarController = function ($scope, Api) {
    console.log($scope);
    console.log($scope.t1);
    console.log($scope.t2);
    console.log($scope.t3);
};

testApp.directive(navigationBar.directives);
testApp.controller(navigationBar.controllers);

Upon inspecting the console logs, you may notice:

Scope {$id: "003", ...}
$$asyncQueue: Array[0]
...
$memId: "003"
...
nav: Object
t1: "hello"
t2: undefined
...

and:

undefined navigation_bar.js:33
undefined navigation_bar.js:34
function (locals) {
                  return parentGet(parentScope, locals);
                }

Why does console.log($scope.t1); not display the value when it should be present in scope->t1: "hello"?

Any insights on why this behavior occurs? Julio seeks assistance on the matter.

Further details:

If replacing the templateUrl with:

template: "Scope Id: {{$id }}, t1: {{ t1 }}"

The output will display:

Scope Id: 003, t1: hello

Alternatively, include a trace within the controller as shown below:

console.log('Scope Id: ' + $scope.$id +  ', t1: ' + $scope.t1);

This will result in:

Scope Id: 003, t1: undefined 

Even though the scope is shared, why is accessing the t1 value proving difficult in the controller? Is further evaluation necessary?

Answer №1

In the realm of scoping, utilizing the @ only assigns the isolated scope with the plain attribute value, which will be in string form and not subject to evaluation.

To delve deeper into the concept of the scoping object, explore the AngularJS Directive documentation within the Directive Definition Object segment.

Answer №2

Understood.

1. The reason for being undefined.

I believe the value is undefined because the controller's binding process was not completed.

2. How to retrieve the value

Since the attribute is passed with the @ symbol, we must set up an observer to monitor the binding. To achieve this, I included the link attribute:

    link: function($scope, $element, $attr) {
        $attr.$observe('tst', function(value){
            console.log('value', value)
            $scope.nav.selection = value
        }
        );
    }

I believe this is the most effective approach.

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 best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

issue with cordova-plugin-geolocation functionality on Android mobile device

Having trouble with the cordova-plugin-geolocation plugin in my ionic/cordova app. It functions perfectly on my browser and iOS device, but when I try it on Android, the map fails to display and does not acquire GPS coordinates. Instead, it times out and t ...

What is the best method for transforming a base64 encoded string into a base64 formatted PDF string?

Could someone please help me with a problem I'm facing? I am utilizing an AngularJS .pdf viewer that displays documents in a modal using base64. Everything works smoothly when the base64 is generated from a .pdf file. The backend (Java) generates th ...

The Angular routing feature seems to be malfunctioning

I have encountered a frustrating issue with AngularJS routing and despite countless searches for solutions, I am still facing the same problem. In my root folder at c:\intepub\wwwroot\angular\, I have three files that I am testing under ...

How to effectively create factories in AngularJS

I stumbled upon this angularjs styleguide that I want to follow: https://github.com/johnpapa/angular-styleguide#factories Now, I'm trying to write my code in a similar way. Here is my current factory implementation: .factory('Noty',functi ...

How to control the activation of ng-click in an Angular application

Modify the condition in ng-click so that it is clickable only if the length is greater than 1. ng-click="filtered.length > 1 ? 'false' : 'true' || showSomething($index)" What needs to be corrected here? ...

Leveraging Bootstrap Modal in a one-page AngularJS application

I am currently working on a single page application in AngularJS using ui.router, and I am looking to incorporate Bootstrap Modals into my app. I have tried following the instructions from this link: http://angular-ui.github.io/bootstrap/#/getting_started ...

Exploring the nuances of AngularJS testing with Jasmine and Karma: delving into the differences between using beforeEach() with

I am new to Jasmine and Karma testing, specifically when it comes to unit testing AngularJS services. When writing specs, I encountered two different ways of injecting a module into the test. 1st Type beforeEach(angular.mock.module("app")); 2nd Type be ...

Deactivate the button and forms in AngularJS

Hey there, I could really use some assistance with this. I'm puzzled as to why my form and buttons aren't disabling during the file upload process. Any help would be greatly appreciated. Thank you! <div> <form name="formImport" ng-s ...

Production environment experiences issues with Angular animations

In my MEAN stack application, I started with Sails.js. Everything was working smoothly during development, especially with angular-animate. However, once I changed the Sails environment to production, I encountered issues. Grunt is set up to concatenate a ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

Count characters in multiple text inputs with AngularJS

Currently, I am developing an Angular JS application with the help of Angular-UI (bootstrap). In this app, there are multiple input boxes where users can enter data, which is then displayed in a div. My goal is to have a character count that applies to al ...

The JQuery loading symbol does not prevent keyboard interactions

I successfully implemented a Jquery busy indicator in my application using the following link: However, I noticed that even though it prevents users from clicking on input elements while loading, I can still navigate to these elements by pressing the tab ...

Troubleshooting Problem with Updating Bootstrap Datepicker in AngularJS

Having trouble updating the date field in the database from my Angular page. Unable to bind the modified date to the database, as the item.ReimbDate still holds the old value. Currently using a bootstrap datepicker for this process. <input type="text" ...

What could be causing the issue with Angular JS's "ng-repeat" not functioning properly?

Presenting my owl crousal: <section id="intro"> <div class="sm-holder"> <div class="sm"> <a href="#"><i class="f ...

Tips on saving checklist values as an array within an object using AngularJS

I need help with storing selected checklist items as an array in a separate object. I want to only store the names of the checklist items, but I am struggling to figure out how to achieve this. Below is the HTML code: <div ng-app="editorApp" ng-contro ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

Issue with touch events for markers in the context of using Google Maps with AngularJS and Onsen UI

I have successfully set up a map with custom markers using JSFiddle. It works perfectly in this demo: https://jsfiddle.net/LdLy6t90/2/ However, when I integrate the same code into my Onsen UI-based app, the touchevents for Google Map markers do not seem t ...