0

在我提供的模板中

<div id="container">
    <textarea name="message"></textarea>
    <button value="send" ng-click="testMethod($parent)">
</div>

在 JS 中:

$scope.testMethod = function(element) {
    console.log("sending message");
    console.log(element); // comes back with an element
    console.log(element.children()); // <-- this throws an exception
    console.log(element.firstChild()); // <-- this throws an exception
}

简单地说,如何通过将元素传递给方法来选择父元素的子元素?

4

2 回答 2

0

Controller methods as the one you have created above should not be manipulating html elements directly. They should only work on objects to which the templates are bound to.

If you want to interact with UI elements in code, you create a directive in AngularJS and the element and its children should be easily accessible in the directive functions. Using attributes you can bind directive scope to controller scope properties and methods and create a wiring between business logic in controller functions and UI elements in directive functions.

There is plenty of documentation on AngularJS on Directives and Scopes, without going through it will be very difficult to achieve the simplest of tasks in AngularJS.

于 2013-05-10T21:05:27.760 回答
0

Ketan 的回答是对的,我想补充一下为什么要获取子元素?您通常不会直接从控制器操作 html,但是您应该并且会更新您的 $scope 数据,这些数据可以推动您页面上的更改。只是在一个普通的旧控制器中举个例子,我们不在乎,element而是在乎范围的数据。

这个简单的示例将在单击按钮时更新文本区域,显示另一个 div。并将一个项目添加到项目数组中。使用 jQuery,我们将通过 javascript 等操作 dom $(el).val()$(el).find()但在角度控制器中,我们不担心 dom,只担心数据:

演示: http: //plnkr.co/edit/aL6p09DrQsUotu7vnceZ

app.controller('MainCtrl', function($scope) {

  $scope.message = "Some data";
    $scope.testMethod = function() {
    $scope.items.stuff.push($scope.message);
    $scope.clicked = true;    
    $scope.message = $scope.message  + ' you clicked me.';
  }
  $scope.items = {stuff:['one', 'two', 'three'],id:1,name:'yeah'}


});

<body ng-controller="MainCtrl">
  <div id="container" ng-form>

    <textarea name="message" ng-model="message"></textarea>
    <button value="send" ng-click="testMethod()">Send</button>
</div>
  <div ng-show="clicked">
    I was clicked
  </div>


  <h2>{{items.name}}</h2>
  <div ng-repeat='item in items.stuff'>
    {{item}}
  </div>

</body>

以上是以控制器为中心,页面上的操作元素是带有指令的角度的一部分,并且没有更多关于您要实现的确切目标的信息(它是否获取表单输入值?)很难为您指明确切的方向对于这个特殊的问题。

于 2013-05-11T15:28:01.630 回答