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

时间:2016-10-28 07:22:15

标签: css angularjs angularjs-directive directive

我正在尝试使用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中的元素时,我得到空id值

enter image description here

请说明如何解决这个问题我需要将指令参数的值绑定到模板

2 个答案:

答案 0 :(得分:0)

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

    (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

答案 1 :(得分:0)

由于您使用的是角度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>