Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-click not working in div

Tags:

Ok, I've been stuck here for a while, and I'm sure it's something relatively dumb

http://plnkr.co/edit/YcBnbE5VCU5rizkDWreS?p=preview

<head>
    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>

    <script >
        function myCtrl($scope,  $window) {
            $scope.vm = {};
            $scope.vm.Courses = [
              { Id: 1, Name: "Course 1"},
              { Id: 2, Name: "Course 2"}
              ];
            $scope.OpenCourse = function(courseId) {
                $window.alert("Called " + courseId);
            }
        }
    </script>
</head>
<body ng-controller="myCtrl">
    <div>  
        <div ng-repeat="course in vm.Courses" ng-click="vm.OpenCourse(course.Id)">
            <div>
                <div>
                    <label>{{course.Name}}</label>
                </div>
            </div>
        </div>
    </div>
</body>

Why isn't ng-click firing here? It seems that this question is asked a lot, but none of the answers seem to help. It also looks like moving the div out of the repeat makes it work, but again, I'm not sure why.

Thanks

like image 201
Carlos Rodriguez Avatar asked Dec 16 '14 19:12

Carlos Rodriguez


People also ask

Can we use NG-click in Div?

Syntax of using ng-click directive There, the button is an element that can be replaced by any other HTML element like a link, span, paragraph, div etc.

What is ngclick?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.

What is ng-click directive in AngularJS give example for ng attributes in detail with an example?

The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can pop up an alert when the button is clicked. Parameter Value: expression: It specifies when the particular element is clicked then the specific expression will be evaluated.

What is controller in Angular 12?

AngularJS ng-controller DirectiveThe ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.


1 Answers

Remove vm.

Result:

<div ng-repeat="course in vm.Courses" ng-click="OpenCourse(course.Id)">

Why?, because everything you set to $scope becomes available on the partial, then you just have to call it.

like image 126
Felipe Pereira Avatar answered Sep 27 '22 23:09

Felipe Pereira