-->

Angular.js passing parameter to directive

2019-08-13 01:24发布

问题:

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:

You were almoust there

just change de directive attribute :

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

Angular expects "-" before uppercase



回答2:

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}}'
    }
});


回答3:

Follow the angular js naming convention

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

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