Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing value of a variable to angularjs directive template function

I am trying to pass a $scope's variable to a directive, but its not working. I am catching the variable in the template function:

app.directive('customdir', function () {

    return {
        restrict: 'E',

        template: function(element, attrs) {
            console.log(attrs.filterby);
            switch (attrs.filterby) {
                case 'World':
                    return '<input type="checkbox">';
            }
            return '<input type="text" />';
        }
    };
});

What I need is the value of variable filterby not the variable name itself.

Plunkr Demo

like image 918
Vikas Singhal Avatar asked Dec 28 '13 04:12

Vikas Singhal


1 Answers

Or like this

app.directive('customdir', function ($compile) {
  var getTemplate = function(filter) {
    switch (filter) {
      case 'World': return '<input type="checkbox" ng-model="filterby">';
      default:  return '<input type="text" ng-model="filterby" />';
    }
  }

    return {
        restrict: 'E',
        scope: {
          filterby: "="
        },
        link: function(scope, element, attrs) {
            var el = $compile(getTemplate(scope.filterby))(scope);
            element.replaceWith(el);
        }
    };
});

http://plnkr.co/edit/yPopi0mYdViElCKrQAq9?p=preview

like image 87
kfis Avatar answered Sep 27 '22 20:09

kfis