Passing value of a variable to angularjs directive template function

后端 未结 3 1459
长发绾君心
长发绾君心 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:17

    First of all, what is a template function? It should be a link function. Second, you're overloading the link function incorrectly, order matters here, its always scope, element, attrs .Third, pass the variable in an isolate scope:

    app.directive('customdir', function ($compile) {
    
        return {
            restrict: 'E',
            scope:{
              filterby:'='
            },
    
            link: function(scope,element, attrs) {
                console.log(scope.filterby);
                switch (scope.filterby) {
                    case 'World':
                        return '';
                }
                return '';
            }
        };
    });
    

    or if you insist on attributes then:

     app.directive('customdir', function ($compile) {
    
            return {
                restrict: 'E',
    
                link: function(scope,element, attrs) {
                    console.log(attrs.filterby);
                    switch (attrs.filterby) {
                        case 'World':
                            return '';
                    }
                    return '';
                }
            };
        });
    

    but in your html:

     
    

    To ensure the variables value gets evaluated first. Finally you should not be manipulating the DOM like that, in fact that link function won't render html as you'd expect. You have a static template and your link function will act as something to set variable values on the template.

提交回复
热议问题