1

I´m learning AngularJS. Now I´m trying the directives. I created a directive but I can´t make it work. I can do it with $scope, but I want to know HOW to do it without it. The code:

<div ng-app="myApp" ng-controller="controls">
    <div the-name></div>
</div>

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

<script>
    var modu = angular.module("myApp", []);

    modu.controller("controls", [function() {
        var self = this;
        self.user = {
            name : "Pedro",
            lastname: "Delgado"
        };
    }]);

    modu.directive("theName", [function() {
        return {
            template: 'Name: {{user.name}}'
        };
    }]);
</script>

An the RESULT is:

Name: 

And I want:

Name: Pedro

Anyone can help me? Thanks a lot!

1 Answer 1

1

It's called controller-as syntax. You need to create an alias to controller in the template:

<div ng-app="myApp" ng-controller="controls as ctrl">
    <div the-name></div>
</div>

and then in directive template use {{ctrl.user.name}}.

But ideally, you isolate the scope of the directive, because you don't want it to know about its surroundings and what controllerAs alias is used.

This version of your directive will be much more reusable:

modu.directive("theName", [function() {
    return {
        scope: {
            user: '='
        },
        template: 'Name: {{user.name}}'
    };
}]);

and usage is:

<div ng-app="myApp" ng-controller="controls as ctrl">
    <div the-name user="ctrl.user"></div>
</div>

So in this case, directive (and template) doesn't know anything about environment it's used (about controller prefix, etc), it only cares that proper user object was passed in it. This is the point of isolated scope.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I was turning crazy! You gave me a BIG view! :D

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.