398

我有一个简单的循环,ng-repeat如下所示:

<li ng-repeat='task in tasks'>
  <p> {{task.name}}
  <button ng-click="removeTask({{task.id}})">remove</button>
</li>

控制器中有一个功能$scope.removeTask(taskID)

据我所知,Angular 将首先渲染视图并用{{task.id}}数字替换插值,然后在单击事件时评估ng-click字符串。

在这种情况下ng-click,完全符合预期,即:ng-click="removeTask(5)".但是......它没有做任何事情。

当然,我可以编写代码task.id$tasks数组甚至 DOM 中获取,但这似乎不像 Angular 的方式。

那么,如何将动态内容添加到循环ng-click内的指令中呢?ng-repeat

4

7 回答 7

754

代替

<button ng-click="removeTask({{task.id}})">remove</button>

做这个:

<button ng-click="removeTask(task.id)">remove</button>

请看这个小提琴:

http://jsfiddle.net/JSWorld/Hp4W7/34/

于 2013-06-11T08:49:39.577 回答
53

真正让我感到困惑的一件事是,当我在浏览器中检查这个 html 时,没有看到它扩展为:

<button ng-click="removeTask(1234)">remove</button>

我看见:

<button ng-click="removeTask(task.id)">remove</button>

但是,后者有效!

这是因为您在“Angular World”中,当您在 ng-click="" Angular 中时,所有准备就绪都知道 task.id,因为您在它的模型中。无需使用数据绑定,如 {{}}。

此外,如果您想传递任务对象本身,您可以喜欢:

<button ng-click="removeTask(task)">remove</button>
于 2014-03-21T19:45:59.680 回答
10

同样值得注意的是,对于在搜索中找到此内容的人来说,这是...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

注意 的值ng-click。传递给的参数goTo()是来自绑定对象 ( ) 的属性的字符串button,但它没有用引号括起来。看起来 AngularJS 为我们处理了这些。我被挂断了几分钟。

于 2014-09-26T04:27:07.390 回答
3

这行得通。谢谢。我正在注入自定义 html 并在控制器中使用 angular 对其进行编译。

        var tableContent= '<div>Search: <input ng-model="searchText"></div>' 
                            +'<div class="table-heading">'
                            +    '<div class="table-col">Customer ID</div>'
                           + ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';

            $timeout(function () {
            var linkingFunction = $compile(tableContent);
            var elem = linkingFunction($scope);

            // You can then use the DOM element like normal.
            jQuery(tablePanel).append(elem);

            console.log("timeout");
        },100);
于 2014-06-25T13:06:28.680 回答
1

上面的答案非常好。您可以查看以下完整代码示例,以便您确切知道如何使用

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

  	app.controller('usersCtrl', function($scope, $http) {
  	  $http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {
  	  	  console.log(response.data)

  	      $scope.users = response.data;
          $scope.setKey = function (userId){
              alert(userId)
              if(localStorage){
                localStorage.setItem("userId", userId)
              } else {
                alert("No support of localStorage")
                return
              }
          }//function closed  
  	  });
  	});
    		#header{
    			color: green;
    			font-weight: bold;
    		}
  <!DOCTYPE html>
  <html>
  <head>
    <title>HyperCrud</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  </head>
  <body>
   	<!-- NAVBAR STARTS -->
      <nav class="navbar navbar-default navbar-fixed-top">
        <div class="container">
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">HyperCrud</a>
          </div>
          <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
              <li class="active"><a href="/">Home</a></li>
              <li><a href="/about/">About</a></li>
              <li><a href="/contact/">Contact</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Apps<span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="/qAlarm/details/">qAlarm &raquo;</a></li>
                  <li><a href="/YtEdit/details/">YtEdit &raquo;</a></li>
                  <li><a href="/GWeather/details/">GWeather &raquo;</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="/WadStore/details/">WadStore &raquo;</a></li>
                  <li><a href="/chatsAll/details/">chatsAll</a></li>
                </ul>
              </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
              <li><a href="/login/">Login</a></li>
              <li><a href="/register/">Register</a></li>
              <li><a href="/services/">Services<span class="sr-only">(current)</span></a></li>
            </ul>
          </div>
        </div>
      </nav>
      <!--NAVBAR ENDS-->
  <br>
  <br>

  <div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">
  		<div class="row">
  			<div class="col-sm-12 col-md-12">
  				<center>
  						<h1 id="header"> Users </h1>
  				</center>
  			</div>
  		</div>

  		<div class="row" >
        <!--ITERATING USERS LIST-->
  		  <div class="col-sm-6 col-md-4" ng-repeat="user in users">
  		    <div class="thumbnail">
  		      <center>
  		      	<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">
  		      	<hr>
  		      </center>
  		      <div class="caption">
  		      	<center>
  			        <h3>{{user.name}}</h3>
  			        <p>{{user.email}}</p>
  			        <p>+91 {{user.phone}}</p>
  			        <p>{{user.address.city}}</p>
  			       </center>
  		      </div>
            <div class="caption">
                <a href="/users/delete/{{user.id}}/" role="button" class="btn btn-danger btn-block" ng-click="setKey(user.id)">DELETE</a>
                <a href="/users/update/{{user.id}}/" role="button" class="btn btn-success btn-block" ng-click="setKey(user.id)">UPDATE</a>
            </div>
  		    </div>
  		  </div>

        <div class="col-sm-6 col-md-4">
          <div class="thumbnail">
            <a href="/regiser/">
             <img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">
            </a>
          </div>
        </div>
  		</div>
      <!--ROW ENDS-->
  </div>


  </body>
  </html>

于 2017-09-23T09:05:39.890 回答
0

这是带有 ng click 功能的 ng 重复并附加滑块

<script>
var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope) {
        $scope.employees = [
            { 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
            { 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
            { 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
            { 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
            { 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
        ]

            //This will hide the DIV by default.
                $scope.IsVisible = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.IsVisible = $scope.IsVisible ? false : true;
            }
        });
</script>
</head>

<body>

<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
                    <div class="MS-content">
                        <div class="item"  ng-repeat="emps in employees"  ng-show = "IsVisible">
                          <div class="subitem">
        <p>{{emps.id}}</p>
        <p>{{emps.name}}</p>
        <p>{{emps.age}}</p>
        </div>
                        </div>


                    </div>
                    <div class="MS-controls">
                        <button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
                        <button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
                    </div>
                </div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
<script src="js/multislider.js"></script> 
<script>

        $('#mixedSlider').multislider({
            duration: 750,
            interval: false
        });
</script>
于 2018-06-12T19:05:13.140 回答
0

HTML:

<div  ng-repeat="scannedDevice in ScanResult">
        <!--GridStarts-->
          <div >
              <img ng-src={{'./assets/img/PlaceHolder/Test.png'}} 
                   <!--Pass Param-->
                   ng-click="connectDevice(scannedDevice.id)"
                   altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}" 
                   onerror="this.src = $(this).attr('altSrc')">
           </div>    
 </div>

Java 脚本:

   //Global Variables
    var  ANGULAR_APP = angular.module('TestApp',[]);

    ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {

      //Variables
      $scope.ScanResult = [];

      //Pass Parameter
      $scope.connectDevice = function(deviceID) {
            alert("Connecting : "+deviceID );
        };
     }]);
于 2017-10-11T11:45:09.493 回答