Angular.js passing parameter to directive

我是研究僧i 提交于 2019-12-13 19:29:34

问题


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>


来源:https://stackoverflow.com/questions/29099814/angular-js-passing-parameter-to-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!