Ways to access input values from a custom directive beyond its scope

How can I access input values outside of a directive (num1, num2) to calculate the result (addition) when a button is clicked? Here is my HTML:

<div ng-app="sumApp" >
  <div ng-controller='sumAppCtrl' > 
    <input  ng-model='num1' type='text'  >
    <span>+</span>
    <input   ng-model='num2'  type='text'>
    <span>=</span>
    <bp-sum></bp-sum>
    <input type="button" value="Sum" ng-click="sumNumbers(num1,num2)" />
   </div>
</div>   

And here is the JavaScript code snippet:

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

sumApp.controller("sumAppCtrl", function ($scope) {

});


sumApp.directive('bpSum',function( ){

return  {

    restrict:'E',
    controller: function($scope, $element){
        $scope.sumNumbers = function(num1, num2){

            var items=[parseInt(num1), parseInt(num2)];
            $scope.addition = _.reduce(items, function(memo, num){ return memo + num; }, 0);
        }
    },
    template:"<input type='text' ng-model='addition' />"

}


})

Answer №1

In my opinion, it is advisable to create the Addition component in the following manner:

<div ng-app="additionApp" >
  <div ng-controller='additionCtrl' >

    <bp-addition></bp-addition>

   </div>
</div>

Custom Directive for Addition

    additionApp.directive('bpAddition', function() {

    return {

        restrict: 'E',
        controller: function($scope) {

            $scope.addNumbers = function(num1, num2) {

                var items = [parseInt(num1), parseInt(num2)];
                $scope.sum = _.reduce(items, function(memo, num) {
                    return memo + num;
                }, 0);
            };

        },
        template: " <input  name='num1' ng-model='num1' type='text'  >" +
            "<span>+</span>" +
            "<input   name='num2' ng-model='num2'  type='text'>" +
            "<span>=</span><input type='button' value='Add' ng-click='addNumbers(num1,num2)' />"+
            "<label>Sum: </label> <input type='text' ng-model='sum' />"
    };


});

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

Troubleshooting the toUpperCase error: A step-by-step guide

Within my Angular JS code, I have a variable: $scope.formData.time This variable holds the format: "12:00:00" In addition, I've created a filter called 'timeApp': .filter('timeApp', function ($filter) { return funct ...

Unable to locate module named 'my'. Unable to locate controller named 'mycontroller'

Hey there, I'm encountering the following issue: Error : Cannot find module with name "my". Moreover, Multiple notes are popping up at this line:- Cannot find module with name my. Cannot find module with name my. Cannot find controller with name ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...

Rearrange lists by dragging and dropping them according to specific criteria

In my AngularJS project, I am utilizing the angular-drag-and-drop-lists library from here to create two lists with the following functionalities: Dragging items from list A to list B Dragging items from list B to list A Reordering items in list A Reorder ...

Transforming Google Maps from using jQuery to AngularJS

If I have a Jquery google map with find address and routing system, my goal is to convert it to an angular google map with more options. The current Jquery google map code looks like this: var directionsDisplay = new google.maps.DirectionsRenderer({ d ...

Utilizing Angular's ngShow and ngHide directives to hide spinner when no data is retrieved

I'm having an issue with the HTML code below. It currently displays a spinner until a list of tags is loaded for an application. However, the spinner continues even if no events exist. I want to make the spinner disappear and show either a blank inpu ...

Tips for incorporating a value within the AngularJS select function

Having an issue with passing a list value in the html select method using AngularJS. Here is my code: app.js $scope.subcategory = function() { var query = "SELECT unit FROM Length;"; $cordovaSQLite.execute(db, query).then(function(res) { ...

Obtain image URL from object properties using AngularJS

Just starting out with Angular JS and I have a question. I'm currently working on a project and I have a solution in mind, but I was wondering if there's a more "angular-esque" approach that I could take. The idea is for each videoid, there wou ...

Create an Angular-UI function that appends a modal inside a <div> element with the class

We are facing an issue with conflicting rule names between our legacy .css and Twitter Bootstrap on our large website. To resolve this conflict, we have implemented a .sass version of Bootstrap and structured everything as follows: .bootstrap-enabled { / ...

Creating an application for inputting data by utilizing angular material and javascript

I am looking to create an application using Angular Material Design, AngularJS (in HTML), and JavaScript. The application should take input such as name, place, phone number, and email, and once submitted, it should be stored in a table below. You can fin ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

Displaying content based on changing conditions fetched from the database

We are currently developing a dynamic form system where users can create custom questions in the admin panel and set conditions to display them based on the values of other questions. ng-show="((UserCode==10003 && Name=='Ankur') ||(State ...

Leveraging AngularJS Service for Seamless Data Sharing

I am currently working on a single-page application (SPA) and trying to dynamically set the browser title based on the route/state. I have a service that updates a variable when each page is loaded, but for some reason, the title in the SPA is not being up ...

AngularJS directive that performs asynchronous validation upon blur

I'm working on developing a directive that validates email addresses provided by users through asynchronous web requests. While the functionality is sound, I've encountered an issue where asynchronous calls are triggered every time a user types a ...

AngularJS - Viewless and Issue-Free

I'm currently working on a project that involves using AngularJS and PHP. I made some changes, but now it's not functioning properly... The issue is that there are no errors in the console, Angular works (I can retrieve its version), but my vi ...

ng-repeat not functioning properly when using track by, filter, and orderBy

I have come across this code snippet. http://jsfiddle.net/0tgL7u6e/ Scripting in JavaScript var myApp = angular.module('myApp',[]); function MyCtrl($scope) { $scope.nameFilter = ''; $scope.contacts = [ {name: 'G ...

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

What is the reason for the filter not displaying the IFRAME?

I have a filter set up to automatically embed YouTube videos for user-generated content by searching for links and verifying if they are valid YouTube videos. If they are, the video should be embedded using standard iframe code; otherwise, it remains just ...

AngularJS- issue with button visibility on 'toolbar' widget

In my angularJS application, there is a page with multiple widgets displayed. When a user clicks on the 'Settings' button on the page (separate from the widgets), a toolbar for each widget appears showing different buttons depending on the widget ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...