ng-click not working - TypeError:undefined不是函数

时间:2014-10-30 07:02:52

标签: jquery angularjs semantic-ui

我使用语义UI来使用AngularJS格式化我的网站。我的控制器设置正常。但它只是不喜欢我的代码的这一部分:

    <div class="ui piled feed segment">
        <h2 class="ui header">
            Comments
        </h2>
        <div class="event" ng-repeat = "comment in comments | reverse">
            <div class="ui green horizontal label">
                {{comment.user}}
            </div>
            <div class="content">
                <div class="summary" ng-click="doSomething()">
                    {{ comment.content }}
                </div>
            </div>
        </div>
    </div>

这是AngularJS代码:

$scope.doSomething = function(){
    alert('blah');
};

基本上,我想在单击内容时执行doSomething()。但由于某种原因它不起作用并给出以下错误:

TypeError: undefined is not a function
    at http://localhost:3000/js/lib/angular.min.js:65:98
    at http://localhost:3000/js/lib/angular.min.js:72:222
    at http://localhost:3000/js/lib/angular.min.js:144:140
    at Object.e.$eval (http://localhost:3000/js/lib/angular.min.js:88:347)
    at Object.e.$apply (http://localhost:3000/js/lib/angular.min.js:88:454)
    at HTMLAnchorElement.<anonymous> (http://localhost:3000/js/lib/angular.min.js:144:122)
    at HTMLAnchorElement.n.event.dispatch (http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js:3:8066)
    at HTMLAnchorElement.r.handle (http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js:3:4774) 

我很不确定这个错误意味着什么,因为通常&#34; undefined&#34;意味着功能定义有问题,但在这里我没有发现任何错误。我在ng-repeat里面点击其他在这个应用程序的地方,它工作正常。是因为语义UI吗?

2 个答案:

答案 0 :(得分:0)

试试这个..

<body ng-app="myApp">
        <div class="ui piled feed segment" ng-controller="myController as ctrl">
            <div class="summary" ng-click="doSomething()">
                {{name}}
            </div>
        </div>

        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
        <script>
        var app = angular.module('myApp',[]);
        app.controller('myController',function($scope){
            $scope.name = "Hi I am a new user Click me!";
            $scope.doSomething = function(){
                alert('blah');
                $scope.msg = 'clicked';
            };
        })
        </script>
    </body>

答案 1 :(得分:0)

我认为它与从ng-repeat内部调用它有关。我忘记了细节,但这是某种范围问题。

而不是$ scope.doSomething,请尝试

$scope.myObject = {};
$scope.myObject.doSomething = function(){//stuff};

然后在HTML中调用myObject.doSomething();

然后,如果我对我的假设是正确的并且确实有效,那么您可能需要查看有关角度实践的文章,这有助于避免此类范围界定问题。

http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html