Passing value of a variable to angularjs directive template function

后端 未结 3 1510
长发绾君心
长发绾君心 2021-02-04 11:03

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\', f         


        
3条回答
  •  天命终不由人
    2021-02-04 11:32

    Template should not contain logic because template is view. Template should only contain binding directives to make the view updated based on changes of the scope (model). Something like this:

    app.directive('customdir', function ($compile) {
    
        return {
            restrict: 'E',
    
            scope:{
              filterby:"="
            },
    
            link:function (scope, element) {
              scope.$watch("filterby",function(newValue){ //logic is out of template
                  if (newValue == "World"){
                    scope.showCheckBox = true;
                  }
                  else {
                    scope.showCheckBox = false;
                  }
              });
            },
    
            template: function(element, attrs) {
             //View should be passive and only listens to changes of model to update it accordingly.
                return ''; 
            }
        };
    });
    

    With this approach, you could even change the input at runtime and the view is updated to reflect the changes.

    DEMO

    If you want to make a decision on which template to use based on some configuration, you should configure it via a normal property, should not access though scope's propery. Simply like this:

    app.directive('customdir', function ($compile) {
    
        return {
            restrict: 'E',
            scope: {
                filterby:"=" //filterby is a separate field used for data binding
            },
    
            template: function(element, attrs) {
                switch (attrs.type) { //view selection configuration should be obtained from the element
                    case 'checkbox':
                        return '';
                }
                return '';
            }
        };
    });
    

    Configure it by passing a normal value:

    
    

    DEMO

提交回复
热议问题