单击AngularJS ng-click时没有响应

时间:2017-11-04 21:02:10

标签: angularjs button angularjs-ng-click

我知道有很多关于这个主题的问题,但找不到我的问题的任何解决方案。我的代码:

更新

   $scope.openOne = function (id) {

    ImageService.getDetails(id).then(function (data) {

        $scope.imageDetail = data;

    }).catch(function (e) {

        var message = [];

    });
}

function getAllImages() {
    ImageService.getImages().then(function (value) {

        $scope.images = value;

        var items = [];

        $(value).each(function () {
            var url = "https://someUrl/" + this.Image[0];
            console.log(url);
            items.push(`
                        <tr>
                            <td><button id="button" ng-click="openOne(${this._id})">${this.ImageName}</button></td>
                            <td>${this.ImageCategory}</td>
                            <td>
                            <img style="width:30%;" ng-src="${url}" alt="The Image is missing">
                            </td>
                        </tr>
                        `);
        });
        $("#body").append(items.join(''));

    }).catch(function (e) {

        var message = [];


    }).finally(function (e) {

    });
}

我在控制器中创建按钮,然后将其附加到DOM。 有人看到错误吗?当我点击按钮时没有任何反应。

2 个答案:

答案 0 :(得分:2)

方法完全错了。

angular中的基本原则是让您的数据模型驱动视图并让角度从模板中编译该视图

更典型的设置会将您的图片数组传递到视图中的ng-repeat

控制器:

function getAllImages() {
    ImageService.getImages().then(function (value) {
        $scope.images = value;
   });
}

查看:

<tr ng-repeat="img in images track by $index">
  <td><button id="button" ng-click="openOne(img.id)">{{img.ImageName}}</button></td>
  <td>{{img.ImageCategory}}</td>
  <td>
    <img style="width:30%;" ng-src="{{img.url}}" alt="The Image is missing">
  </td>
</tr>

答案 1 :(得分:0)

您需要在此处添加$compile服务,这会将ng-click等角度指令绑定到您的控制器范围。例如

app.controller('yourController', function($scope,$compile) {
var button = '<button id="button" ng-click="openOne(${this._id})">${this.ImageName}</button>';
items.push(button);
$("#body").append(items.join(''));
var temp = $compile(button)($scope);
$scope.openOne = function(){
   alert('Yes Click working at dynamically added element');
 }

});
相关问题