css - 如何将指令范围值绑定(bind)到angularjs中的模板

标签 css angularjs angularjs-directive directive

我正在尝试使用 angularjs 指令为 div 绑定(bind) 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 值是空的

enter image description here

请说说怎么做我需要将指令参数的值绑定(bind)到模板

最佳答案

您不应在 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

关于css - 如何将指令范围值绑定(bind)到angularjs中的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40300063/

相关文章:

css - Twitter Bootstrap 导航栏折叠功能不起作用

html - 使用左对齐时表格从 div 出来

jquery - 居中对齐 CSS 框翻转动画 UL

angularjs - Angular 指令测试 - 错误 : [$injector:modulerr] Failed to instantiate module?

javascript - 清除功能没有做任何事情

angularjs - 追踪无限摘要错误

angularjs - Protractor - 描述未定义

javascript - AngularJs 将 promise 响应作为参数传递给函数

angularjs - 将变量传递给指令的属性

angularjs - Angular : calling controller function inside a directive link function using &