dhana lakshmi dhana lakshmi - 1 month ago 6
AngularJS Question

how to bind directive scope value to template in angularjs

I am trying to bind the id property value for a div using angularjs directive

I want a div container where id of the container will be passed as the parameter from the directive

<!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>


but when i see inspect the element in bowser i am getting empty id value

enter image description here

please say how to go about it i need to bind the value of directive parameter to the template

Answer

You should not use the scope in the template outside of link function.

    (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>

Please run the above snippet and check the id