非指令控制器函数内的访问属性值

时间:2015-06-18 11:25:59

标签: javascript angularjs

HTML内容,

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

Js内容,

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

打印

helloworld

在控制台中。 我正在将上面的代码迁移到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
})

有人可以帮助我使用hello控制器函数参数和内容吗?

3 个答案:

答案 0 :(得分:3)

如果您要切换到AngularJS,则必须完全重新考虑您的应用程序 - 很难从使用选择和DOM操作的现有应用程序进行彻底检修。 Angular通常用于避免这些。因此,您应该问自己为什么需要绑定到事件而不是使用数据绑定/视图模型。

这太过分了,所以要解决你的问题,你可以使用指令。

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

答案 1 :(得分:1)

Angular方式是在控制器范围中定义值

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

但是,如果你真的需要从html定义data-href并以角度代码访问它,你需要考虑使用directive而不是控制器

答案 2 :(得分:0)

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

function Ctrl($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

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

JSFIDDLE