简体   繁体   中英

Unable to access AngularJS attribute in directive

I'm currently trying to implement a very simple directive in AngularJS. In the end, I want to be able to use the directive like this:

<share-buttons url="google.com"></share-buttons>

My directive looks like this (coffee script):

module.directive 'shareButtons', () ->


    controller = ['$scope', ($scope) ->

        $scope.share = () ->
            console.log $scope.url

    ]

    return {
        restrict: 'EA'
        scope: {
            url: '=url'
        }
        templateUrl: viewpath_common('/directives/share-buttons')
        controller: controller
    }

And here's my template (Jade):

.social-icons
    button.btn.btn-li(ng-click="share()")
        i.fa.fa-linkedin.fa-fw

When I click the button, the correct function is called ($scope.share), but the only thing logged is undefined .

Can you help me?

its because your url attribute is two way data bound with "="

so it's looking for a scope variable like this:

$scope.google.com =  // should be some value.

to be passed from the controller to the directive.

If you want a string to be passed, use "@" for one way binding

scope: {
        url: '@'
}

Note: you can also access it via attributes in the link function of the directive (which you don't have above)

// like so
restrict: 'EA'
scope: {
    url: '@'
}
templateUrl: "someURL",
link: function(scope, elem, attrs) {
    console.log(attrs.url);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM