Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access attribute value inside non-directive controller function

HTML content,

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

Js content,

$("body").on('click', 'button', function(){
    console.log($(this).attr("data-href"));
});

This prints

helloworld

in the console. I am migrating the above code to angularjs,

<div ng-controller="hello">
  <button data-href="helloworld">Show href Value</button>
</div>

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

app.controller("hello", function(){
  //someone help me with the services that are to be injected and 
  //and what logic goes here to print the data-href attribute value
})

Can someone help me with the hello controller function arguments and contents?


2 Answers

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 () {
    return function (scope, elem, attr) {
        elem.bind("click", function () {
            console.log(attr.showHref);
        });
    };
});
like image 73
Explosion Pills Avatar answered Jun 28 '26 19:06

Explosion Pills


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

like image 25
Kirill Slatin Avatar answered Jun 28 '26 19:06

Kirill Slatin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!