繁体   English   中英

另一个ng-click()无法正常工作

[英]Another ng-click() not working as expected

我确信这是基本的东西,但是我找不到。 我正在尝试将数据发送回控制器。 我相信ng-click事件不会触发。 这是我调试问题的尝试。 我相信我已将其简化为简单警报的基本要点。

这是控制器和局部视图

 angular.module('FieldApp', []) .controller('FieldCtrl', function($scope, $http) { $scope.createField = function($scope, $http) { alert("Create Field"); } }) 
 <script src="./bower_components/angular/angular.js"></script> <script src="./bower_components/angular-route/angular-route.js"></script> <div class="container" ng-app="FieldApp" ng-controller="FieldCtrl"> <button type="button" class="btn btn-primary btn-lg btn-block" ng-click="createField()">Add Field</button> </div> <script src="./js/field.js" charset="utf-8"> 

干杯

该函数中的依赖项参数是不必要的。 只需这样声明函数:

$scope.createField = function() { ... }

并且您需要引用$window依赖项以显示警报:

$window.alert("Create Field");

不要忘记在控制器的依赖项列表中包含$window .controller('FieldCtrl', function($scope, $http, $window) { )。

但是最好只做console.log("Create Field"); 代替。

窗口引用不是必需的。 这就是我编写您的代码的方式。 我不知道代码中到底发生了什么,但是通常最好的做法是为模块设置变量。

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>

    var app = angular.module('FieldApp', []);

    app.controller('FieldCtrl', ['$scope', function($scope) {
        $scope.createField = function() {
             alert("Create Field");   
        };

    }]);
</script>

</head>
<body>
    <div ng-app="FieldApp">
        <div ng-controller="FieldCtrl">
            <button ng-click="createField()">Add field</button>
        </div>
    </div>
</body>
</html>

这个代码段在我的机器上工作。

我看不到您的代码有任何问题。 我从中创建了一个jsFiddle: https ://jsfiddle.net/gcsgggcw/

我刚刚从您的html中删除了javascript链接:

<div class="container" ng-app="FieldApp" ng-controller="FieldCtrl">
   <button type="button"  ng-click="createField()">Add Field</button>
</div>

原因一定是其他原因。 您是否检查了所有JavaScript文件是否都已正确加载到浏览器中?

解决方案是未正确设置变量名称格式的情况。 我在一个文件中有myApp,在另一个文件中有MyApp。 自从我使用文本编辑器代替Visual Studio以来已有很多年了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM