Skip to content Skip to sidebar Skip to footer

Access Attribute Value Inside Non-directive Controller Function

HTML content, Js content, $('body').on('click', 'button', function(){ console.log($(this).attr('data-href')

Solution 1:

If you are switching over to AngularJS you will have to start rethinking your app entirely -- it's difficult to make a complete overhaul from an existing app that is using selection and DOM manipulation. Angular is typically used to avoid these. Thus, you should ask yourself why you need to bind to an event rather than using data bindings / the view model.

That's too much to get into here, so to solve your immediate problem you could use a directive.

<button show-href="helloworld">Show href Value</button>

// `data-` prefixes stripped from directives as part of Angular normalization
app.directive("showHref", function () {
    returnfunction (scope, elem, attr) {
        elem.bind("click", function () {
            console.log(attr.showHref);
        });
    };
});

Solution 2:

Angular way would be to define value in controller scope

<button data-href="{{myUrl}}" ng-click="helloClick()">Show href Value</button>
....
app.controller("hello", function($scope){
     $scope.myUrl = 'helloworld';
     $scope.helloClick = function(){
          console.log($scope.myUrl);
     }
})

However if you really need to define data-href from html and get access to it in angular code that you need to consider using a directive instead of a controller

Solution 3:

var$scope;
var app = angular.module('miniapp', []);

functionCtrl($scope) {
    $scope.clickEvent = function(obj) {

        // Log the obj to see everything
        console.log(obj);

        // Alert just the data value
        alert(obj.target.attributes.data.value);

    }
};

HTML

<divng-app="miniapp"><divng-controller="Ctrl"><ang-click="clickEvent($event)"class="exampleClass"id="exampleID"data="exampleData"href="">Click Me</a></div></div>

JSFIDDLE

Post a Comment for "Access Attribute Value Inside Non-directive Controller Function"