ng-click不起作用 - AngularJs

时间:2015-03-08 06:38:26

标签: javascript angularjs html5 angularjs-ng-click

我已经检查了这里提供的所有解决方案,但它对我没有帮助。

我正在尝试将AngularJs中的按钮显示为html,但ng-click不适用于<a><button>个标签。我在Eclipse中工作,它包含许多内置模块。请帮帮我。以下是示例代码:

   <!DOCTYPE html>
<html>
<head>
    <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="contrl">
<a href="" ng-click="testFunc1()">Link1</a>
<div id="id1">Text1</div>
<p id="id2">Text2</p>
</div>

<script>
    function contrl($scope,$http,$location){
            xyz = '<button type="submit" ng-click="testFunc2()">Link2</button>';
            document.getElementById("id1").innerHTML = xyz;

            $scope.testFunc1 = function() {
            document.getElementById("id2").innerHTML = "abc";
            };
            $scope.testFunc2 = function() {
            document.getElementById("id2").innerHTML = "xyz";
            };
    }
</script>
</body>
</html>

当我通过angularJs传递它时,只有ng-click属性不起作用。即使href属性也在同一个案例中工作。当我使用Eclipse时,所有必需的模块已经设置在不同的文件中。我在两周内使用angularJs,除了遇到这个问题外,一切正常。

3 个答案:

答案 0 :(得分:0)

不完全确定你要做什么,但这样的事情会更好:

<!DOCTYPE html>
<html>
<body>
<div ng-app="myApp" ng-controller="contrl">
<p><a href="" ng-click="testFunc1()">Link1</a></p>
<div id="id1">{{ val1 }}</div>
<p id="id2">{{ val2 }}</p>
</div>

<script>
  var myApp = angular.module('myApp',[]);

  myApp.controller('contrl', ['$scope', '$http', '$location', function($scope, $http, $location) {

      $scope.val1 = "text1";
      $scope.val2 = "text2";

      $scope.testFunc1 = function(){
            $scope.val1 = 'New Value';              
      }

      $scope.testFunc2 = function(){      
            $scope.val2 = 'Second New Value';                         
      };
  }]);

</script>
</body>
</html>

答案 1 :(得分:0)

您的代码是有人会遵循的最基本的方法。它没有错,唯一的问题是您似乎使用较新版本的角度进行开发,或者您忘记包含任何内容。

最近发布的angular版本不支持您的应用程序开发模式。

我使用到1.2.26,它有效。

Check demo here

您还使用了innerHTML,以及document.getElementById。

这些都不是必需的。阅读有关绑定和角度的其他最佳部分的更多信息。

答案 2 :(得分:0)

这是因为angular并不知道您使用普通javascript引入的ng-click。 因此,如果您想在html中执行此操作,可以像这样编写脚本:

    function contrl($scope){


        $scope.text = 'text2';
        $scope.testFunc1 = function() {
            $scope.text = "abc";
        };
        $scope.testFunc2 = function() {
            $scope.text = "xyz";
        };
};

如果您仍想从脚本中插入html,请查看此处:AngularJS : Insert HTML into view