如何在控制器中获取子DOM的$ attrs数据?

时间:2014-04-29 08:32:18

标签: javascript angularjs dom angularjs-scope

假设我有一个控制器和许多具有自己的data属性的子DOM。

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p data-test-val='Brian'>Hello {{name}}!</p>
  </body>

</html>

我想要像这样访问data-test-val

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

app.controller('MainCtrl', function($scope, $attrs) {
  $scope.name = $attrs.testVal;
});

但是,由于name为空,它似乎不起作用。

http://plnkr.co/edit/V1Leit8U7r2k4CZDGaGa?p=preview

如何访问同一范围的子DOM中的任何data属性?

感谢。

3 个答案:

答案 0 :(得分:1)

你在控制器中弄乱了属性获取方面的指令。

指令:

.directive('directiveName', function() {
    return {
        link: function($scope, $elem, $attrs) {
            // get $attrs stuff here
        }
    }
});

答案 1 :(得分:0)

创建一个名为&#34; dataTestVal&#34;的单独指令,然后您就可以访问该标记的属性。

示例代码:

<html ng-app="ExampleApp">
  <head>
    //required libraries, scripts
  </head>
  <body ng-controller="ExCtrl">
    <div data-testval data="person"></div>
  </body>
  <script>
    angular.module('ExampleApp',[]);

     angular.module('ExampleApp")
      .controller("ExCtrl",function($scope){
         $scope.person = {
           name:"afd",
           age : 30
         };
     });
    angular.module('ExampleApp")
      .directive("dataTextval",function(){
         return{
           restrict:'A',
           scope:{
            data : '='
           },
           link:function(scope,element,attrs){
            //you can gain access to element and its attributes
            //scope.data is nothing but person details, which is declared in controller
           }
         }
       });


  </script>
</html>

答案 2 :(得分:-1)

试试这个:

var ele = document.getElementsByTagName('p');
$scope.name = ele.getAttribuete('data-test-val');