Restricted scope / Effective method for passing an array to the directive user

Picture this scenario where a custom directive is referenced in myHtml.tpl.html:

<my-directive></my-directive>

This directive starts with an isolated scope.

Naturally, there's a controller tied to myHtml.tpl.html.

I aim to pass a computed array from the isolated scope to the controller's scope.

One approach could be:

<my-directive arrayToCompute="arrayToCompute"></my-directive>

The isolated scope (in the directive) would look like this:

scope: {arrayToCompute: "="}

and the controller would begin with an empty array declaration:

$scope.arrayToCompute = [];

However, this solution might not seem very elegant...

Is there a better option?
(Note that I want to retain the scope isolation of the directive).

Answer №1

To implement a strict decoupling, consider using a notify-callback. For example:

app.controller('AppCtrl', ['$scope', function ($scope) {
  $scope.raw      = [1, 2, 3];
  $scope.computed = null;

  $scope.setComputed = function setComputed(computed) {
    $scope.computed = computed;
  };
}]);

app.directive('myDirective', function () {
  return {
    restrict: 'E',
    scope: {
      input:     '=?',
      onCompute: '&'
    },
    link: function (scope) {
      function compute(input) {
        return input.slice().reverse();
      }

      scope.$watch('input', function (nv) {
        scope.onCompute({
          computed: compute(nv)
        });
      });
    }
  };
});

Include the following in your code:

<body data-ng-controller="AppCtrl">
  <my-directive input="raw" on-compute="setComputed(computed)"></my-directive>

  <pre>{{ raw | json }}</pre>
  <pre>{{ computed | json }}</pre>
</body>

View demo here: http://jsbin.com/satavesuhiqu/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

Adjust the burger menu color based on the background color of the section

Currently, I am working on creating a hamburger menu component with fixed positioning using the 'fixed' property. The menu icon consists of three white lines by default, but I want them to change to black when placed in a white section. I have tr ...

extract elements from dataset

Attempting to splice an array but encountering index issues var kode_pelayanan = []; function deleteKodePelayanan(index){ kode_pelayanan.splice(index, 1); console.log(kode_pelayanan); } Experimented in the console with an array for kode_pelayanan ...

Avoid storing js files in cache during the development phase

When I use django runserver for development, I encounter the issue of my javascript file being cached. It's difficult to determine if the file is cached or not unless I manually add alert or console.log statements each time I make a change just to che ...

Enhancing website performance with a combination of Google Analytics outbound click tracking and a JavaScript speed bump

I have successfully integrated the universal GA for tracking outbound clicks, however I have also added a "speed bump" pop-up message that appears when a user clicks on an offsite link. The JavaScript code for this is as follows: (specific to bank client - ...

Issue with sizing and panning when using a combination of Three.js and CSS3Renderer

This issue is specific to Chrome. Here's what I have experimented with: I am utilizing the webGL renderer to position a plane geometry in a 3D environment using threejs. This particular code is running within a class, with the scene as one of its me ...

Get a file from a node.js web server by clicking a button to initiate the download

I am a beginner in nodejs and I am working on creating a web server using nodejs to host some static files. Here is the code I have used for this purpose: var http = require('http'); var finalhandler = require('finalhandler'); var ser ...

JSON format used to convert information from a webpage

I came across a URL in my textbook, , which directs to a page providing the original page's content in JSON format. Intrigued, I attempted to format another webpage's content into JSON using the same method, as my professor also shared a link in ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Exporting JSON models with textures from Blender using THREE.JS

I am currently utilizing the mrdoob Blender Export Plugin (io_mesh_threejs) for exporting to Three JS, but I am encountering an issue where the exported .js or .dae objects do not contain any reference to the texture map files. I am wondering if there is a ...

How come I am receiving a null value for isMatch from bcrypt compare even though the two password strings match exactly?

Currently, I am attempting to authenticate a user based on a password. My approach involves using bcrypt compare to check if the user's requested password matches one stored in a MongoDB database. Despite the passwords being identical, I keep receivin ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

The Next.js 404 error page seems to be malfunctioning. Any ideas on what might be causing this issue?

Whenever I attempt to access a non-existent route, the home page loads without changing the URL. My expectation was to see a 404 error page. To handle this issue, I created a custom error page called pages/_error.js import Page404 from './404'; ...

Tips for inserting a jQuery snippet into a universal file

Seeking some advice on integrating jQuery code into my JavaScript file, which is located at . The code snippet I am attempting to add looks like this: $(document).ready(function() { queue = new Object; queue.login = false; var $dialog = $ ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

How to create a CSS animation that gradually darkens a background image during a

Currently in the process of constructing a page with an intriguing background image: body { background:url(images/bg.png) center center no-repeat fixed; -webkit-background-size:cover; -moz-background-size:cover; -o-background-size:cover; ...

Tips for submitting an AJAX response using a form

Steps Taken I have implemented an ajax call to retrieve checkboxes as follows: <script> $(document).ready(function(){ $("#place").change(function(){ var id = $(this).val(); alert(id); $.ajax({ ...

Cleaning up unwanted objects in THREE.js webGL

Our app utilizes THREE.js to showcase 3D body meshes. We have a special object named MeshViewer that manages the rendering process; within the initialize method, we establish this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBu ...

sending data from an AngularJS application to an MVC controller in JSON format containing multiple arrays

Currently, I am working on a project that involves using AngularJS and MVC. I am transferring data from an AngularJS controller to my MVC controller using $http.post(). At the moment, I am using a single object or JSON array to retrieve data as follows: pu ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...