Transforming a string in AngularJS to a "controller as" approach using $parse

How can I modify foo.callbacke to reference the timerController.callbacke method?

<div ng-app="timerApp" ng-controller="timerController as foo">
<div ng-repeat="item in [1,2,3,4]">
    <div watcher="{'seconds': 'foo.callbacke'}">
        {{seconds}}
    </div>
</div>

If you prefer: http://jsfiddle.net/e86e05a1/ (open console)

Answer №1

In your directive's scope, the controller method is readily available for access without the need to use the controllerAs alias. Simply pass the method name instead of accessing it through index notation, try using $eval on the scope.

Please Note:

It is recommended to use $observe unless you are dealing with attribute interpolation like {{something}}.

Sample Markup:

<div watcher="{'seconds': 'callbacke'}">

Example Code:

angular.forEach(new_watchers, function(callback, k) {
     watchers.push($scope.$watch(k, function() {
         return $scope.$eval(callback)($scope, $element);
     }));
});

View Demo in Fiddle

Answer №2

You can't simply pass a function reference to a directive in that manner. Instead, you need to create an isolated scope within the directive and then map the parent controller's function to the directive's scope using =. Give this approach a try.

HTML

<div callbacke="callbacke" watcher>
    {{seconds}}
</div>

JS

.directive('watcher', ['$compile', '$parse', function($compile, $parse) {
    'use strict';

    return {
        restrict: 'A',
        transclude: false,
        scope: {
            callbacke: '='
        },
        controller: ['$scope', '$element', '$attrs', function($scope, $element, attrs) {
            var watchers = [];
            console.log($scope.callbacke);
            ...
            ...
        }]
        ...
        ...
    };
}]);

Demo http://jsfiddle.net/e86e05a1/1/

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 kind of output should a Server Side Component generate?

Recently, I decided to incorporate the NextPage type from Next.js into my component writing routine after hearing it's a beneficial practice. However, I discovered that it only functions properly with client-side components. When attempting to utilize ...

Angular 2 lacks compatibility with SVG

I have a website where I want to include SVG images inline with my HTML using Angular 2. However, when I try to load the SVG icons within a component, they do not display correctly. Instead, I see the following: https://i.sstatic.net/Ozo6E.png You can vi ...

Struggling to dynamically generate class names with clsx in combination with TailwindCss

Greetings! I am a JavaScript developer who is not very skilled yet, working with React and Next. Specifically, I am using this template When it comes to declaring component class names, I have been using a utility function that combines tailwind-merge and ...

Send an object from AngularJS to an MVC controller and bind it to a corresponding class object

Trying to map an object from AngularJS to a custom C# class in an MVC controller, but encountering issues with the class object showing up as null. Here's the code snippet: $scope.Get = function () { var EService = [{ id: $scope.Id, ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

When attempting to send coordinates to the Polyline component in React Native, an error is encountered stating that NSNumber cannot be converted to

Trying to pass coordinates from BackgroundGeolocation.getLocations() is causing an issue. Upon passing the coordinates, I encounter the following error message: JSON value '-122.02235491' of type NSNumber cannot be converted to NSDictionary I ha ...

Dynamic modal in Vue JS with custom components

Within the news.twig file {% extends 'layouts.twig' %} {% block content %} <section class="ls section_padding_bottom_110"> <div id="cart" class="container"> <cart v-bind:materials=" ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

The elements within the array have not been defined

Why is the results array showing as undefined? I am having trouble displaying the objects inside the results array. I have attempted to do so with console.log(data.results[0].bodyColor) but encountered an error. When I try accessing (data.results), it ret ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

The "disabled" attribute is no longer recommended, please utilize "disable" instead

Lately, after upgrading AngularJS, I have been receiving a warning whenever I open a ui.bootstrap modal. The warning in Chrome-beta 44 says: angular.js:11655 Use of "disabled" attribute has been deprecated, please use "disable" I'm curious if this i ...

Guide to utilizing the THREE.OBJExporter

I've come across this post, however, when I am utilizing var material = new THREE.MeshBasicMaterial( { color: 0xffff00 } ); var mesh = new THREE.Mesh( totalGeom, material ); THREE.OBJExporter.parse( mesh ); Error message shown is: Uncaught Typ ...

The PopupControlExtender in ajaxToolkit seems to be malfunctioning when used with a textbox that has Tinymce

I recently built a website using ASP.NET, and I have a feature where a small tooltip appears on the right side of a text box when the user focuses on it. To achieve this, I am using the ajaxToolkit:PopupControlExtender in my code. <asp:TextBox ...

What could be causing my JavaScript loop to only display the final value?

Story Behind the Game In my latest project, I am delving into the world of creating a captivating 2D side-scrolling game using HTML and JavaScript. To ensure smooth gameplay, I have opted to incorporate ES6 for efficient management of all game objects. C ...

Integrating eBay API with Node.js

Hello, I am new to Node.js and I could really use some assistance with exporting console log data to an HTML page. I came across a helpful example on GitHub at this link: https://github.com/benbuckman/nodejs-ebay-api My current issue is that although I h ...

The issue arises when interfaces are extended by another interface

Is there a way to have classes that implement both the Observer and Comparable interfaces together? interface Comparable<T> { equals: (item: T) => boolean; } interface Observer extends Comparable<Observer> { notify: () => void } ...

Implementing Knockout.js with JqueryUI Autocomplete: Access the complete object instead of just the value

I have implemented a custom binding for a JQueryUI auto complete feature that works well. However, I am looking to modify it so that it returns the Item object, which can then be pushed to another array. Can someone provide guidance on how to achieve this ...

Using Angular to iterate over JSON fields containing hyphens

<span ng-repeat="doc in docs"> <p>{{doc.posted-Time}}</p> Instead of the actual value from the JSON, all I am getting is a 0. Is there a method to avoid this issue with the '-'? In my normal practice, I would utilize doc[&a ...

Sending JSON array from PHP to jQuery AJAX

Currently, I am working on an experimental project where I need to search for a product in a MySQL database using the product name and retrieve the price in the 'price input' field and sell price in the 'sellprice input' field. You can ...

Using VueJS for Dynamic Class Binding

Using Vue version 3.0.5. I have a component named Cube.vue where I am attempting to dynamically assign a blue or green class to a child element. The component has been created and imported into a specific page, however, I am facing issues getting the con ...