在AngularJs中,如何在单击事件中调用函数

6

我的代码结构如下:

  1. main.html-加载所有模块-声明ng-app和主控制器-包含div标签load-div
  2. file1.html ...(所有其他HTML文件)-仅包含
    /子标签,并在事件(例如单击)中加载到main.html中的load-div中

现在在其中一个文件,比如file3.html中,我有一个复选框。当单击该复选框时,我想打开一个模态窗口——一个将被提交的表单。现在这是我的代码:

file3.html

    <div>
        <input type="checkbox" name="your-group" value="unit-in-group" onclick="toggleModal();"/>Unit-in-group
        <modal title="some title" visible="showModal">
            <form role="form">
                <div class="form-group">
                    <label for="email">Email address</label>
                    <input type="email" class="form-control" id="email" placeholder="Enter email" />
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" id="password" placeholder="Password" />
                </div>
                <button type="submit" class="btn btn-default">Submit</button>
            </form>
        </modal>
    </div>

现在我已经在main.html中声明的主控制器中编写了以下代码。
$scope.showModal = false;
  $scope.toggleModal = function(){
    $scope.showModal = !$scope.showModal;
 };

期望的行为是当我的file3被加载时,我会在屏幕上看到一个复选框,当我点击它时,它会打开一个模态窗口,但是实际情况是我在同一页上看到了模态表单字段和复选框,当我点击它时,我得到了一个Angular异常,显示showModal未定义。

我错在哪里了?

3个回答

8

只需要使用Angular语法:ng-click用于点击事件,ng-show用于显示隐藏。

 <input type="checkbox" name="your-group" value="unit-in-group" ng-click="toggleModal();"/>Unit-in-group
 <modal title="some title" ng-show="showModal">

其他选项:

在这种情况下,您也可以使用ng-change代替ng-click,但这不会有太大的区别。

或者您可以使用ng-modelng-model="showModal")并完全摆脱您的切换函数示例


4

我曾遇到过类似的问题。

要检测点击事件,可以使用Angular语法:(click)="toggleModal();"。

<input type="checkbox" name="your-group" value="unit-in-group" (click)="toggleModal();"/>

我希望这能有所帮助。

1
另一种方法是使用ngChange指令来检测复选框是否被选中。
<input type="checkbox" name="your-group" value="unit-in-group" ng-change="toggleModal();"/>

模态框的代码与其他答案提供的相同

 <modal title="some title" ng-show="showModal">

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