首页 > 解决方案 > 如何让 ng-click 在 AngularJs 中工作

问题描述

我为按钮添加了一些 ng-click 事件,但是当我尝试单击按钮时,test() 函数不会触发。我做了一切来解决这个问题,但我做不到。

<div ng-controller="bilgiyarismasiCtrl" ng-repeat="x in sorular">
    <div class="row text-center" style="margin: 50px 250px 50px 250px;">
        <div class="col-md-12" style="padding:90px; background-color:gray; color:white;">
            {{ x.SORU_ICERIGI }}
        </div>
        <div class="col-md-6" style="padding:50px; background-color:white;">
            <button ng-click="test()" class="btn btn-primary btn-lg">{{ x.A_SIKKI }}</button>
        </div>
        <div class="col-md-6" style="padding:50px; background-color:white;">
            <button ng-click="test()" class="btn btn-primary btn-lg">{{ x.B_SIKKI}}</button>
        </div>
    </div>
    <br /><br /><br />
</div>

角代码:

var app = angular.module("module", ["ngRoute"]);

app.config(function ($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl: "bilgiyarismasi.html",
            controller: "bilgiyarismasiCtrl"
        });
});

app.controller("bilgiyarismasiCtrl", function ($scope, $http) {

    $http.get("http://localhost:53438/api/BilgiYarismasi/GetSorular")
        .then(function (response) {
            $scope.sorular = response.data;
        });

    $scope.test = function () {
        console.log(1)
    }    
});

标签: angularjs

解决方案


仅供参考,您上面的代码没有调用控制器,因此您无法通过单击任何按钮获得输出。

使用以下代码:

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

    
ngApp.controller('bilgiyarismasiCtrl',function($scope, $http){
$scope.sorular = [];
 /* $http.get("http://localhost:53438/api/BilgiYarismasi/GetSorular")
            .then(function (response) {
                $scope.sorular = response.data;
            }); */
    $scope.test = function () {
            console.log('test')
        }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


<div ng-app="app">
    <div ng-controller="bilgiyarismasiCtrl">
        <div >
        
         <div class="row text-center" style="margin: 50px 250px 50px 250px;">
        <div class="col-md-12" style="padding:90px; background-color:gray; color:white;">
            {{ x.SORU_ICERIGI }}
        </div>
        <div class="col-md-6" style="padding:50px; background-color:white;">
            <button ng-click="test()" class="btn btn-primary btn-lg">{{ 'x.A_SIKKI' }}</button>
        </div>
        <div class="col-md-6" style="padding:50px; background-color:white;">
            <button ng-click="test()" class="btn btn-primary btn-lg">{{' x.B_SIKKI'}}</button>
        </div>
    </div>
    <br /><br /><br />
    </div>
    </div>
</div>

您尚未在模板文件中包含 ng-app。我制作了一个demo,你可以看看。希望这对您有所帮助。


推荐阅读