Angularjs: how to pass scope variables to a directive?

前端 未结 3 489
误落风尘
误落风尘 2021-02-01 17:19

I am trying to use directive to create and append several tags to a

as shown below:

module.directive(\'createControl\', function(){
  re         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 17:27

    If v.type may change (i.e., you really need to use interpolation -- the {{}}s), use @charlietfl's or @Joe's answser, depending on the type of scope you want your directive to have.

    If v.type will not change (i.e., your link function only needs to get the values once, and those values are guaranteed to be set when your link function runs), you can use $parse or $eval instead. This has a slight performance advantage in that no $watches are created. (With $observe() and =, Angular sets up $watches, which are evaluated every digest cycle.)

    app.directive('createControl', function ($parse) {
        return function (scope, element, attrs) {
            console.log('$eval type:', scope.$eval(attrs.createControl));
            var type = $parse(attrs.createControl)(scope);
            console.log('$parse type:', type);
            element.text('Directive text, type is: ' + type);
        }
    });
    

    demo

提交回复
热议问题