icode icode - 3 months ago 32
AngularJS Question

angularjs controller access directive scope value

I have this controller with directive inside my html code. The directive have scope value I would like access from the parent controller and show in the html. Hope my example code give you a simple overview of what I'm trying to achieve.

I know this work using $rootScope.showvalue = 'pass text'; in the directive works but don't know if this is the best solution.

app.directive('customdir', [function() {
return {
restrict: "E",
scope: {
showvalue: "="
},
link: function(scope, el, attrs) {
scope.showvalue = 'pass text';

}
};
}]);

app.controller('mycontroller', function($scope) {
alert($scope.showvalue);
});



<html>
<div ng-controller="mycontroller">
<custom-dir></custom-dir>

/* Show scope value from custom dir */

{{showvalue}}
</div>
</html>

Answer

Since you're binding the directive's isolate scope showvalue property via bidirectional binding, you can simple pass the parent scope property in as an attribute

<customdir showvalue="showvalue"></customdir>

<p>{{showvalue}}</p>

Demo ~ http://plnkr.co/edit/W5k0hgDElklseOvjwRsS?p=preview


If you want the HTML to be <custom-dir>, you'll need to rename your directive to 'customDir'.