如何使范围我绑定到指示链接中的模板



在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?谢谢!


使用范围。$ 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
            });
        }
    };
});

您可以使用范围传递一些值。

在模板中:

parameter="someValueCanPassTo"

在指令中:

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

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

请参阅https://developer.mozilla.org/en-us/docs/web/guide/html/html/using_data_attributes有关此信息。

编辑:数据将从属性中删除。因此,您可以使用数据 - 但是您必须为代码添加标识符。

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

在您的指令中声明范围,例如scope: { identifier: '=' },您应该可以

最新更新