【问题标题】:Access attribute value inside non-directive controller function访问非指令控制器函数内的属性值
【发布时间】:2015-06-18 11:25:59
【问题描述】:

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 控制器函数的参数和内容吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    如果您要切换到 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);
            });
        };
    });
    

    【讨论】:

      【解决方案2】:

      角度方式是在控制器范围内定义值

      <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 而不是控制器

      【讨论】:

      • 需要ng-click="helloClick()"
      【解决方案3】:
      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

      【讨论】:

        猜你喜欢
        • 2016-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多