如何将指令范围值绑定到 angularjs 中的模板

how to bind directive scope value to template in angularjs

我正在尝试使用 angularjs 指令

绑定 div 的 ID 属性 值

我想要一个 div 容器,其中容器的 ID 将作为参数从指令

传递
<!DOCTYPE html>
<html lang="en"  ng-app="directivesModule">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>


<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>


<script src="scripts/angular.js"></script>
<script>

    (function() {

        var zdMap =  function() {
            var template = '<div id="{{scope.mapId}}" > abd</div>'
            function link(scope, elem, attrs) {
                console.log("**********************"+scope.mapId)

            }
            return {
                scope: {
                    mapId:'@'

                },
                link: link,
                template: template
            };
        };




        angular.module('directivesModule', [])
                .directive('zdMap', zdMap);

    }());

</script>


</body>
</html>

但是当我在 bowser 中看到 inspect 元素时,我得到的 id 值是空的

请说明如何去做 我需要将指令参数的值绑定到模板

您不应在 link 函数之外的模板中使用 scope

    (function() {

        var zdMap =  function() {
            var template = '<div id="{{mapId}}" > abd</div>'
            function link(scope, elem, attrs) {
                console.log("**********************"+scope.mapId)

            }
            return {
                scope: {
                    mapId:'@'

                },
                link: link,
                template: template
            };
        };




        angular.module('directivesModule', [])
                .directive('zdMap', zdMap);

    }());
<!DOCTYPE html>
<html lang="en"  ng-app="directivesModule">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>


<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>




</body>
</html>

请运行上面的片段并检查id

由于您使用的是 angular 1.5+,我建议您使用 .component 而不是 .directive

  (function() {

        var zdMap =  function() {
            var template = '<div id="{{$ctrl.mapId}}" > abd</div>'
            function controller() {console.log(this.mapId)}
            return {
                bindings: { // HERE !!
                    mapId:'@'

                },
                controller: controller
                template: template
            };
        };




        angular.module('componentModule', [])
                .component('zdMap', zdMap); // here!!!!

    }());

HTML:

<!DOCTYPE html>
<html lang="en" ng-app="componentModule">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <meta charset="UTF-8">
    <title>Test</title>
</head>
<body>
<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>
</body>
</html>