2

I'm a newbie at Angular, so don't be surprise if the answer to this question is pretty basic.

I'm trying to encapsulate a map in a directive, the map will have some custom behavior: I want it to communicate with a Service to retrieve all the points related to a merchant.

So I want to pass the merchant as a parameter to the directive:

This is the HTML:

<div ng-app="myApp">
    <div ng-controller="Ctrl1">
        <p>Ctrl 1: {{merchant1}}</p>
        <map merchantDetails="{{merchant1}}"></map>
    </div>
</div>

This is the javascript:

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

myApp.controller('Ctrl1', function ($scope) {
    $scope.merchant1 = "foo"
});

myApp.controller('Ctrl2', function ($scope) {
    $scope.merchant2 = "bar"
})
    .directive('map', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs, controller) {
            scope.merchant2 = attrs.merchantDetails;
        },
        scope: {
            merchantDetails: "@"
        },
        template: 'Ctrl2: {{merchant2}}'
    }

});

The problem is that scope.merchant2 at the template never gets updated. I would like it to have "foo", or at worst "bar", not blank.

When I debug this in Chrome, controller Ctrl2 initialization is never executed. Why? I would expect it to be done before the link phase.

How do I do to get the "foo" value passed to Ctrl2?

The jsfiddle is available here.

1

3 Answers 3

4

You actually don't need the second controller. I update the fiddler, please check if it's what you need:

https://jsfiddle.net/e7cfcakv/7/

<div ng-app="myApp">
    <div ng-controller="Ctrl1">
        <p>Ctrl 1: {{merchant1}}</p>
        <map merchant-details="{{merchant1}}"></map>
    </div>
</div>

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

myApp.controller('Ctrl1', function ($scope) {
    $scope.merchant1 = "foo"
});

myApp.directive('map', function () {
    return {
        restrict: 'E',
        link: function (scope, element, attrs, controller) {
            scope.merchant2 = scope.merchantDetails;
        },
        scope: {
            merchantDetails: "@"
        },
        template: 'Ctrl2: {{merchant2}}'
    }
});
Sign up to request clarification or add additional context in comments.

Comments

3

You were almoust there

just change de directive attribute :

<map merchant-details="{{merchant1}}"></map>

Angular expects "-" before uppercase

Comments

1

Follow the angular js naming convention

just change the attribute "merchantDetails" to "merchant-details"

 <map merchant-details="{{merchant1}}"></map>

Comments

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.