innerhtml ng-click不在控制器内触发

时间:2018-01-05 09:47:59

标签: angularjs

HTML:

<div id="selectedFiles"></div>

控制器:

var selDiv = document.getElementById("selectedFiles");


selDiv.innerHTML +=                         
                    "<span style='margin-right: 5px;'>" +
                    "<button id='deleteButton' ng-
                    click='deleteFile()' " +
                    "style='width: 70px;height: 25px;margin-left: 
                    10px;padding: 1px;'>Delete</button>" +
                    "</span><br/><br/>";

// this was added later but still no luck
$compile($(selDiv).contents())($scope);

function deleteFile() {
        // not getting fired
        console.log("inside delete file1");
    }

1 个答案:

答案 0 :(得分:0)

你应该怎么做,IMO:

&#13;
&#13;
botchat.css
&#13;
var app = angular.module('myApp', []);

app.controller('ctrl', function($scope) {
  $scope.files = [];

  $scope.deleteFile = function(file) {
    var index = $scope.files.indexOf(file);
    
    if (index > -1) {
      $scope.files.splice(index, 1);
    }
  }
});

angular.module("myApp").directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = [];
        
        for (var i = 0; i < elem[0].files.length; i++) {
          files.push(elem[0].files[i])
        }
        
        ngModel.$setViewValue(files);
      })
    }
  }
});
&#13;
&#13;
&#13;

here获得指令。