Bhumiraj Darbar
Bhumiraj Darbar

Reputation: 21

How to pass the value from controller to directive in angular js

Helllo,

i want to pass the one value from controller to directive in angularjs. how would i pass the value and display it in directive .

in Html Section

in controller section my controller name is docontroller.

$scope.name = "world";

angular.element(document.querySelector('#carControls')).append($compile( mydirectivename as tag )($rootScope));

i have to pass my variable as well as controller in which i can get direct access in my directives it is my directive used in controller and appended to html in my directive section

myApp.directive('Controls', function ($compile, $rootScope, $timeout, $window) {
    var linker = function (scope, element, attrs) {
alertr('name' + scope.name);      
  $timeout(function () {

            scope.controlClass = 'fa fa-pause';
            var ControlsTemplate =

                '<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-backward"></i></button>'+
                '<button ng-click="doPlayOrPause()" class="btn btn-default btn-sm margin-r-10 text-center"><i id="play-pause" ng-class="controlClass"></i></button>'+
                '<button class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-forward"></i></button>'+
                '<button ng-click="doStop()" class="btn btn-default btn-sm margin-r-10 text-center"><i class="fa fa-stop"></i></button>';

            element.html(ControlsTemplate);
            $compile(element.contents())(scope);



        });  
    };
    return {
        restrict: "E",
        replace: true,
        link: linker
    };
});

in return i passed controller :'docontroller bt i cant find my name in scope'

Upvotes: 1

Views: 4224

Answers (2)

Ebin Manuval
Ebin Manuval

Reputation: 1255

in you controller

$scope.yourValue="myValue";

in your directive

app.directive('myDirective',function(){
 return {
        restrict: 'E',
        scope: {
            yourValue: '='
        },
})

in your dom

<my-directive your-value="yourValue"></my-directive>

checkout this js fiddle

Upvotes: 3

Dinesh Shah
Dinesh Shah

Reputation: 1233

If you are not using isolated scope than you can access parent controller $scope.

you can also use $rootScope.

like

Controller :

app.controller("demoCtrl",function($scope,$rootScope){

   $rootScope.xyz = "test";
// call your directive , value will be accessible in directive
})

Directive :

app.directive(...,function($rootScope){
 return   {
 // extra code omitted.

  // get your value here like
  // var abc =  $rootScope.xyz;

}
)

Upvotes: 0

Related Questions