Philip Bursh February 2016

How to get input values outside the custom directive

I need to get input values outside directive(num1,num2) to count the result in it(addition) on click to the button. What is the proper way to do it? 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 js code:

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

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

});


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

return  {

    restrict:'E',
    controller:
        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' />"

}


})

Answers


pac-man February 2016

According to me..you should develop the component for Addition like this

<div ng-app="sumApp" >
  <div ng-controller='sumAppCtrl' > 

    <bp-sum></bp-sum>

   </div>
</div> 

Directive

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

    return {

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

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

                var items = [parseInt(num1), parseInt(num2)];
                $scope.addition = _.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='Sum' ng-click='sumNumbers(num1,num2)'' />"+
            "<label>Sum is : </label> <input type='text' ng-model='addition' />"


    };


});

Post Status

Asked in February 2016
Viewed 3,273 times
Voted 14
Answered 1 times

Search




Leave an answer