Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS evaluate $rootScope variable in directive template

I have a directive that creates an input field. I need to set the ng-model attribute of this input field to the value of a $rootScope variable. The reason behind this is that I want the input field to be in the layout, and bind to different models depending on what page is loaded. I thought I'd set this global variable in each controller and access it in the Directive.

ATM the variable is hard coded

App.run(function($rootScope){
    $rootScope.mymodel = 'search.name';
})

And the Directive

Directives.directive('inputFilter', function(){
    return{
        restrict: 'E',
        replace:true,
        controller: function($scope, $rootScope){
            console.log($scope.mymodel);
            console.log($rootScope.mymodel)

        },
        template: '<input class="filter" type="text" ng-model="mymodel" placeholder="Nach filtern">'
    }

});

It gets rendered as

<input class="filter ng-pristine ng-valid" type="text" ng-model="mymodel" placeholder="Filter">

and the text inside the input field is the value of mymodel variable. The console.log shows

search.name
search.name  

Could anyone please shed some light on this issue?

like image 820
glasspill Avatar asked Mar 15 '13 13:03

glasspill


1 Answers

What I think you want is

template: '<input class="filter" type="text" ng-model="' 
  + $rootScope.mymodel + '" placeholder="Nach filtern">'

Fiddle.

Note that you will need to inject $rootScope into your directive:

Directives.directive('inputFilter', function($rootScope) {
like image 81
Mark Rajcok Avatar answered Oct 17 '22 06:10

Mark Rajcok