AngularJS : Pass $scope variable as directive attribute

后端 未结 4 1913
失恋的感觉
失恋的感觉 2021-02-13 14:27

I\'m trying to pass the $scope variable values to a custom directive as attribute, but it\'s not working.

Here is the HTML code:

4条回答
  •  耶瑟儿~
    2021-02-13 15:15

    In directives, attributes are just strings.

    In a template function, all you can do is use the string value of the attribute. If you want to use the evaluated or interpolated value of the attribute, you have a few options:

    1) Use an isolated scope

    app.directive('checkList', function() {
        return {
            restrict:'E',
            scope: {
                name: '&'
            }
            template: '
    Yes
    {{name()}} No' link: function(scope, elem, attrs) { } }; });
    • {{q.question}}

    2) Inject $interpolate or $parse to evaluate the interpolation or expression manually in the link function

    app.directive('checkList', function($interpolate) {
        return {
            restrict:'E',
            template: '
    Yes
    {{name}} No' link:function(scope,elem,attrs){ scope.name = $interpolate(attrs.name)(scope); } }; });
    • {{q.question}}

    2a) And finally, $parse

    app.directive('checkList',function($parse){
        return {
            restrict:'E',
            template: '
    Yes
    {{name}} No' link:function(scope,elem,attrs){ scope.name = $parse(attrs.name)(scope); } }; });
    • {{q.question}}

提交回复
热议问题