Reputation: 509
How can I pass the value of directive to the controller or pass a variable from directives to controller. Thank you.
This is my code. It has the variable under the $observe function
.directive("groupId", function () {
return {
replace: true,
link: function(scope, element, attrs) {
attrs.$observe('groupId', function(value) {
myVal = value;
});
}
};
})
Upvotes: 1
Views: 414
Reputation: 1260
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-controller="MainCtrl">
<table>
<!--* groupIdValue value is passing from controller to directive
* and my-val is returned back from directive to controller
* that value is available to controller from ControllerVar variable *-->
<tr group-id="{{groupIdValue}}" my-val="ControllerVar"></tr>
</table>
controller variable: {{ControllerVar}}
</body>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.groupIdValue = '123345';
}).directive("groupId", function() {
return {
replace: true,
restrict: 'A',
scope: {
myVal: "=myVal"
},
link: function(scope, element, attrs) {
attrs.$observe('groupId', function(value) {
scope.myVal = value;
});
}
};
})
</script>
</html>
Here you can use ControllerVar
in your controller as $scope.ControllerVar
.
Upvotes: 1