【问题标题】:GetElementById equivalant in angular jsangularjs中的GetElementById等价物
【发布时间】:2016-07-12 11:27:28
【问题描述】:
<div>
    <input id="txt"  type="text" placeholder="Choose File" />
    <input type="file" id="selectedFile" class="hidden" onchange="ChangeText(this, 'txt');" />
    <span>
        <button type="button" onclick="document.getElementById('selectedFile').click();">Browse</button>
    </span>
</div>

我只想要 Angular js 中的点击事件。谁能告诉我?

我只想要 Angular js 中的点击事件。 谁能告诉? 代码在注释中

【问题讨论】:

  • 请把问题描述得更清楚。如果你想在角度点击事件,那么需要使用 ngclick 事件
  • 我的代码在 js 中,对于浏览按钮,我已经给出了 onclick 事件,以便它会像这样获取 selectedfile id 元素, 所以我想要 angular js 中的函数
  • 我不想在 Angular js 中使用 document.getElementById

标签: javascript angularjs


【解决方案1】:

好的,在我可能没有完全阅读您的问题之前。现在我有了,我想这就是你要找的东西:https://plnkr.co/edit/pfjU5B17qCzwHKoG4iTN?p=preview

.controller('Upload', ['$scope', function($scope) {
    this.input;

    this.browse = function() {
        this.input.click();
    };
}])
.directive('fileUpload', [function() {
    return {
        'restrict':'E',
        'controller':'Upload',
        'controllerAs':'upload',
        'templateUrl': './upload.html',
        'link':function($scope, $element, $attribute, upload) {
            upload.input = $element.find('input')[1];
        }
    };
}]);

在指令的链接函数中,我将输入注入控制器。控制器只需向节点触发点击事件,从而调用文件浏览器。

编辑:我个人不会使用输入来显示文件,而是显示所有选定文件的更通用列表,并在可能的情况下进行预览。这样你只需要使用第一个输入:)

很抱歉没有更好地阅读您的问题,希望对您有所帮助。

【讨论】:

    【解决方案2】:

    这不是角度方式,DOM 应该调用代码中的函数,而不是您的代码轮询 DOM 中的事件。

    <script>
      $('#btn').click(function() {
        doTheThing();
      });
    </script>
    <button id="btn">Do the thing!</button>
    

    对比

    <my-button  ng-click="{{ MyBtnCtrl.doTheThing() }}">Do the thing!</my-button>
    

    使用控制器

    function MyButtonController() {
      this.doTheThing = function() {
        alert('I\'m doing the thing!')
      };
    }
    

    编辑: 因为我现在只看到您的代码,所以您显示的代码不是角度代码。如果您想使用 Angular,请查看以下链接:

    我更喜欢 codeschool 来帮助您入门,因为它更具交互性并提供分步指南。

    【讨论】:

    • 代替getElementById,我可以在angular js函数里面写什么
    • 你没有。您应该使用控制器编写指令,并简单地从您的 DOM 中调用控制器的功能。使用 Angular 时,您应该“从不”在代码中使用 DOMNode。可能会有一些例外,但始终不要在控制器中引用您的 DOM。
    【解决方案3】:
    <div>
        <input id="txt"  type="text" placeholder="Choose File" />
        <input type="file" id="selectedFile" class="hidden" onchange="ChangeText(this, 'txt');" />
        <span>
            <button type="button" onclick="click();">Browse</button>
        </span>
    </div>
    
    $scope.click = function() {
            document.getElementById('selectedFile').click()
    };
    

    【讨论】:

    • 在函数内部使用 document.getElementById('selectedFile').click()。我们可以在不使用 getElementByID 的情况下做同样的功能吗
    猜你喜欢
    • 2018-09-29
    • 2014-09-24
    • 2018-05-12
    • 2016-04-06
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多