简体   繁体   中英

Why does ng-click not fire in components template?

I am picking up Angular for a project of mine and am having trouble getting my first steps right.

Specifically, I can get a list of items to display via a component and appropriate template, but I can not figure out how to trigger ng-click events using the component model. Many similar problems to this have been answered on SO but I have followed the many corrections and suggestions without progress and need some advice.

file: customerList.js
function CustomerListController($scope, $element, $attrs, $http) {
    this.customerList = [
        { name: 'Arya' },
        { name: 'No One' },
    ];

    this.yell = function(customer) {
        console.log("customer customer, we've got a click");
    };
}

angular.module('myApp').component('customerList', {
    templateUrl: 'customerList.html',
    controller: CustomerListController,
});

And its template:

file: customerList.html
<div class="customer"
    ng-repeat="customer in $ctrl.customerList"
    customer="customer"
    ng-click="$ctrl.yell(customer);">
        Welcome home, {{customer.name}}!
</div>

Even when I set ng-click="console.log('click detected');" , I get no console log.

I believe this is sufficient information to diagnose but please let me know if you need more.

Thanks!

First of all, console.log will not work directly in an angular expression. You can't use window functions directly in expressions.

Second, I would recommend using controllerAs syntax as it's a newer school way of doing things. Try accessing the controller with your controllerAs alias in the ng-click() expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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