Chirag Suthar Chirag Suthar - 1 year ago 70
AngularJS Question

How to pass $scope in Angular directive

I am new to AngularJS. I want to return template to directive with addition and subtraction of two numbers. I am passing

$scope
in function but it is not working.

I'm learning from Angular Modules with Directive

here is the code :

<html>

<head>
<title>Angular JS </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>

<body>
<div ng-app="Compl">
<input type=number ng-model="no1" placeholder="Enter the First Number" />
<input type=number ng-model="no2" placeholder="Enter the First Number" />
<NoSum></NoSum>
<NoSub></NoSub>
</div>
<script>
var app = angular.module("Compl", []);
app.directive("NoSum", function($scope) {
return {
template: "Sum of Two Number" + ($scope.no1 + $scope.no2)
};
});
app.directive("NoSub", function($scope) {
return {
template: "Sub of Two Number" + ($scope.no1 - $scope.no2)
};
});
</script>
</body>

</html>

Answer Source

If you're not using isolated scope, you should be able to just use no1 and no2 directly in the template. assuming those are variables in the parent scope.

<script>
    var app = angular.module("Compl", []);
    app.directive("noSum",function(){
        return{
            template : "Sum of Two Number {{(no1 + no2)}}"
        };
    });
    app.directive("noSub",function(){
        return{
            template : "Sub of Two Number {{(no1 - no2)}}"
        };
    });
</script>

You should also rename your directives, since capitalized letters have special meaning in angular. So with my changed names above, your html should look like this:

<no-sum></no-sum>
<no-sub></no-sub>

Here is a Plunker showing it working as expected

This works because without isolated scope, your directives inherit the scope of their parent, which in your case is the $rootScope. If you used isolated scope instead, you would have to pass in the variables through html attributes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download