1

I'm trying to create a directive that will output a HTML-template that is using data from a controller.

In sample.js I've added a module, controller and directive

var app = angular.module("myApp", []);

app.controller("MyCtrl", function($scope) {
    $scope.someProperty = true;
})

app.directive("myElement", function() {
    return {
        restrict: "E",
        scope: {name: "@"},
        template:
            '<div ng-show="someProperty">' +
            '    <p>This element is called {{name}}</p>' +
            '</div>',
        replace : true,
        transclude : false
    }
})

I'm using the element with the following HTML

<!DOCTYPE html>
<html ng-app="myApp">
    <head>
         <meta charset="UTF-8">

         <script type="text/javascript" src="angular.min.js"></script>
         <script type="text/javascript" src="sample.js"></script>
    </head>
    <body ng-controller="MyCtrl">
        <div><my-element name="Mark"></my-element></div>
        <div><my-element name="Vink"></my-element></div>
    </body>
</html>

Since the controller is created in the body, I would expect the child-element to be able to use it's properties/methods. But there's no data showing up (without the ng-show, the data shows fine).

In this simplified sample I could move the ng-show to the DOM-element in the HTML, but in my actual application this wouldn't be an option. I really need my directive to be able to use properties (and methods) from my controller.

Is this possible? And what did I miss to get it to work?

1 Answer 1

2

Since you are using an isolated scope you have to declare someProperty to use it like this

app.directive("myElement", function() {
    return {
        restrict: "E",
        scope: {
          name: "@",
          someProperty: "="
        },
        template:
            '<div ng-show="someProperty">' +
            '    <p>This element is called {{name}}</p>' +
            '</div>',
        replace : true,
        transclude : false
    }
});

and you can use it like this

<my-element name="Vink" some-property="someProperty"></my-element>
Sign up to request clarification or add additional context in comments.

1 Comment

To add to this answer, this is from the angular documentation: "As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.