【问题标题】:change value of a variable with ng-change function [duplicate]使用 ng-change 函数更改变量的值
【发布时间】:2019-12-20 17:16:44
【问题描述】:

我在一个对象 c.data.requiredAttachmentUploaded = false 中有一个项目,当在 <input type="file" > 中选择一个文件时,我需要将其设为“真”

所以我试图用 ng-change 来做,但它不起作用,甚至 console.log 也不起作用。 ng-change 适合这个任务吗?

APP.JS

app.controller('taskSummaryAndAction', [ 
  function() {

    c = this; //declare c internally 
    c.data = {}; //setup our data object (To be used in later steps)

    c.data.requiredAttachmentUploaded = false;

    c.attachmentChange = function() {  
      console.log('Hello');
      c.data.requiredAttachmentUploaded = true;
    }; 

  }
]);

HTML

<div ng-controller="taskSummaryAndAction as c">

    Input File here :

    <input type="file" ng-change="attachmentChange()"
           ng-model="c.data.requiredAttachmentUploaded">

</div>

我可以使用 jQuery 轻松做到这一点,但我需要使用 AngularJS 做到这一点。 我什至没有在控制台中收到错误。

【问题讨论】:

  • docs 说:“注意:并非所有提供的功能都适用于所有输入类型。具体来说,input[file] 不支持通过 ng-model 进行数据绑定和事件处理。"
  • ng-change="c.attachmentChange()"

标签: javascript angularjs


【解决方案1】:

我成功了,我了解到 &lt;input type="file" &gt; 的 ng-change 用法不同 所以我对我的控制器和我的 HTML 进行了一些更改。

JS:

app.controller('taskSummaryAndAction', [ '$scope',
  function($scope) {
    c = this; //declare c internally 
    c.data = {}; //setup our data object (To be used in later steps)
    c.data.requiredAttachmentUploaded = false;

    $scope.attachmentChange = function() {  

      c.data.requiredAttachmentUploaded = true;
      console.log(c.data.requiredAttachmentUploaded);
    }; 

  }
]);

HTML

<input type="file" onchange="angular.element(this).scope().attachmentChange()" ng-model="file">

【讨论】:

  • 你不应该使用angular.element(this).scope()
  • @BillP 是的,你是对的。我又被卡住了,我没有意识到,我正在使用 onchange 。我需要使用ng-change
猜你喜欢
  • 2017-04-08
  • 2017-09-19
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2013-04-02
  • 2020-04-29
相关资源
最近更新 更多