使用ng-model输入文本并通过JavaScript设置值

3

我有一个显示可删除数据列表的表格。在该表格中,我有复选框供用户选择要删除的数据。当点击删除按钮时,将出现一个模态框,在该模态框中有一个带有ng-model的输入文本框。它的值将通过javascript/jquery设置。我希望使用angularjs $http请求将其删除。我观察到只有在文本字段中输入文本时才能正常工作。但是当通过javascript设置时,它不起作用。这是模态框内的输入字段。

   <input class="form-control" id="id" ng-value=""  ng-model="Thing.id" /> 

还有模态框:

 <script type="text/javascript">
$('#delete_item').on('show.bs.modal', function (event)  { 
  var button = $(event.relatedTarget) 
  var modal = $(this)  
  var ids=getID_delete.call();
    $('.modal-body #id').val(ids) ;
    modal.find('.modal-body #message').text('Are you sure you want to delete it?'); 
  });</script>

下面是AngularJS控制器的代码:

mainApp.controller('equipmentController', ['$scope', '$http', function($scope, $http) {
$scope.equipments=[]
$http.get(BASE_URL+'Equipment/getAllEQs').success( function(response) {
                       $scope.equipments = response

                    });
$scope.delete = function(Thing) {
$params = $.param({
  "id": Thing.id

})
return $http({
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    url:BASE_URL+'Equipment/DeleteEQ',
    method: "POST",
    data: $params,
  })
    .success(function(response) {
     $('#delete_item').modal('hide');
    $scope.equipments = response
    });
 }
}]);

请问你能展示一下如何调用Angular方法 delete(thing) 的代码吗?传到函数delete的数据是正确的吗? - Abhilash Augustine
@AbhilashPA,当我使用alert(Thing.id)时,结果是undefined。但是当我手动输入数据到输入框中时,它可以正常工作。 - d_unknown
你试过我的答案了吗? - Abhilash Augustine
2个回答

2
首先,你不应该在AngularJS中使用JQuery,这不是一个好的做法。每当你需要与DOM交互时,你应该使用指令"Thinking in AngularJS" if I have a jQuery background? 然而,你可以使用以下方法作为解决方法:
<input type="text" class="form-control" id="id" ng-value=""  
 ng-model="Thing.id" ng-model-options="{ updateOn: 'change' }" />  

在你的 JQuery 代码中应该使用:
$('.modal-body #id').val(ids).trigger("change");

这将强制模型在输入更改时进行更新。
这里是一个 jsFiddle示例

1

你可以从jQuery代码中访问你的Angular控制器作用域。因此,你可以直接将值设置到作用域中。

var controllerElement = document.querySelector('[ng-controller="your_controller"]');
var controllerScope = angular.element(controllerElement).scope();
controllerScope.Thing.id = ids;

你可以强制Angular编译器将jQuery编写的HTML编译,以更新视图。
controllerScope.$apply( function(){
    controllerScope.Thing.id = ids;
});

所以您的代码应该是这样的:
<script type="text/javascript">
    $('#delete_item').on('show.bs.modal', function (event)  { 
      var button = $(event.relatedTarget) 
      var modal = $(this)  
      var ids=getID_delete.call();
      var controllerElement = document.querySelector('[ng-controller="your_controller"]');
      var controllerScope = angular.element(controllerElement).scope();
      controllerScope.$apply( function(){
          controllerScope.Thing.id = ids;
      });
      modal.find('.modal-body #message').text('Are you sure you want to delete it?'); 
    });
</script>

没有错误显示,也没有设置任何值。输入文本框中只是空白。 - d_unknown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接