Sunday, 15 May 2011

Angularjs show directive based on controller variable -



Angularjs show directive based on controller variable -

i have directive loads template this:

app.directive("sidebar", function(resource_url) { homecoming { templateurl: resource_url + 'sidebar.html' }; });

the html looks this:

<sidebar ng-controller="sidebarctrl" ng-show="ready"></sidebar>

and controller:

app.controller('sidebarctrl', function($scope, authservice) { $scope.service = authservice; $scope.ready = false; $scope.user = {}; $scope.$watch('service.getuser()', function(value){ $scope.user = value; $scope.ready = true; }); });

is there way create directive utilize controller's scope variables? or what's mutual method utilize in case?

there 2 main ways access scope variables within directive, first 1 enable scope inheritance within of directive using scope: true

app.directive("sidebar", function(resource_url) { homecoming { scope: true, templateurl: resource_url + 'sidebar.html' }; });

which allows inherit outer scope within of directive, the other way attach controller directive using controller: sidebarctrl:

app.directive("sidebar", function(resource_url) { homecoming { controller: 'sidebarctrl', templateurl: resource_url + 'sidebar.html' }; });

or, can write service hold scope variables , allow access different parts of code same instance of variable.

https://docs.angularjs.org/guide/services

angularjs angularjs-directive angularjs-scope

No comments:

Post a Comment