【问题标题】:how to get the scope I bind to template inside directive link如何在指令链接中获取我绑定到模板的范围
【发布时间】:2016-12-28 09:25:26
【问题描述】:

在 html 中,我在指令中绑定 id:

<my-customer data="id"></my-customer>

在js中:

angular.module('Main', [])
.controller('Controller', ['$scope', function($scope) {
    $scope.id= 'divId';
}])
.directive('myCustomer', function() {
    return {
        restrict: 'E',
        scope: {
            data: '='
        },
        template: '<div id="{{data}}"></div>',
        link: function(scope,element,attrs){
            console.log(document.getElementById('divId'));
        }
    };
});

它可以在模板中显示数据,但控制台显示未定义,因为模板尚未加载数据,我如何在数据加载后获取 dom? 谢谢!


使用scope.$watch解决问题:

在 html 中:

<my-customer param="id"></my-customer>

在js中:

angular.module('Main', [])
.controller('Controller', ['$scope', function($scope) {
    $scope.id= 'divId';
}])
.directive('myCustomer', function() {
    return {
        restrict: 'E',
        scope: {
            param: '='
        },
        template: '<div id="{{param}}"></div>',
        link: function(scope,element,attrs){
            scope.$watch('param',function(){
                console.log(document.getElementById(param)); //get the dom
            });
        }
    };
});

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

您可以使用范围传递您的 someValue。

在模板中:

parameter="someValueCanPassTo"

在指令中:

scope: {
    parameter: '='
},
link: function(scope, element, attrs) {
    $watch('parameter', function() {
        element.attr('my-attr', scope.parameter);
    });
}

【讨论】:

  • 你在@VamcherylZhang
【解决方案2】:

尽量不要使用data="",因为这是一个保留属性

请参阅https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes 了解更多信息。

编辑: data- 将从属性中删除。所以你可以使用数据——但你必须为你的代码添加一个标识符。

因此,如果您将 html 更改为 data-identifier="id"

并在您的指令中声明scope: { identifier: '=' } 之类的范围,您应该没问题

【讨论】:

  • 谢谢!我会注意的。在链接函数中使用 scope.$watch() 可以解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多