Access to the $ scope variable inside the directive template and the $ scope.variable update controller

I created a simple directive with an input element and a range. Using the directive, I created two custom elements with a selection area. Now I'm trying to get the sum of the data entered in the input element of the directive. But I really can’t understand how to do this. Here is my controller and directive:

angular.module('mapp',[]) .controller('ctrl',['$scope',function($scope){ $scope.total = 0; }]) .directive('customElement',function(){ return { restrict: 'E', scope:{ data: '=info' }, template: '<input type="text" ng-model="data1">\ <span>{{data1}}</span>' } }); 

I want to summarize the data1 all directive elements and update $scope.total . Here is the HTML code:

 <div ng-app="mapp"> <div ng-controller="ctrl"> <custom-element info="a"></custom-element> <custom-element info="b"></custom-element> <br/> <br/> Total: <span>{{total}}</span> </div> </div> 

Here is a demo

+7
angularjs angularjs-scope angularjs-directive
source share
3 answers

Here is the working violin

 angular.module('mapp', []) .controller('ctrl', ['$scope', function ($scope) { $scope.total = 0; $scope.a = 0; $scope.b = 0; $scope.$watchCollection('[a,b]', function () { console.log('watch'); $scope.total = $scope.a + $scope.b; }); }]) .directive('customElement', function () { return { restrict: 'E', scope: { data: '=info' }, template: '<input type="number" ng-model="data">\ <span>{{data}}</span>' } }); 

Version without $ watch

Version with ng-repeat

+9
source share

Total: <span>{{a+b}}</span> this will also work in html without using $watch or a function from the controller

+3
source share

Here you can do with $ watch

controller

 .controller('ctrl',['$scope',function($scope){ $scope.test = {}; $scope.test.a = 0; $scope.test.b = 0; $scope.$watch('test',function(newVal,oldVal){ $scope.total = $scope.test.a + $scope.test.b },true) $scope.total = 0; }]) 

Change directive ng-model="data1" to ng-model="data"

 template: '<input type="number" ng-model="data">\ <span>{{data}}</span>' 

Working script

0
source share

All Articles