I tried using various methods to bind a function to an event, but it seems that the event does not work out even in banal examples. Perhaps a stupid question, help me figure it out.

<a href="" ng-click="console.log('test')"> 

or so:

 <a href="" ng-click="UserController.update(user)"> 

I write this in the controller file:

 (function () { 'use strict'; angular .module('app') .controller('UserController', ['$scope', '$sce', '$window', '$location', '$rootScope', '$cookieStore', 'UserService', UserController]); function UserController($scope, $sce, $window, $location, $rootScope, $cookieStore, UserService) { var self = this; // VARS // self.users = []; self.update = update; function update(user) { return 'test'; } } })(); 

    1 answer 1

    This is all due to the fact that everything that is written in the view is taken from $scope .

    Since there is neither the console property, nor the UserController property in the controller's osprey, the angular is silently swallowing the error and does not output anything.

    In order for the console to work, in the controller you need to add it to the skop, like this:

     $scope.console = console; 

    In order for the option with the controller to work, you need to use controllerAs

     ng-controller="UserController as UserController" 

    At the same time, a field with the name UserController referring to the current controller instance is added to the skop.

    This entry is equivalent to the following in the code:

     $scope.UserController = this; 

    Examples:

    With installation in code:

     (function() { 'use strict'; angular .module('app', []) .controller('UserController', ['$scope', UserController]); function UserController($scope) { var self = this; // VARS // self.users = []; self.update = update; $scope.console = console; $scope.UserController = this; function update(user) { console.log('update->test'); return 'test'; } } })(); 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script> <div ng-app="app"> <div ng-controller="UserController"> <a href="" ng-click="console.log('test')">Console.log('test')</a> <br/> <a href="" ng-click="UserController.update(user)">UserController.update(user)</a> </div> </div> 

    With controllerAs syntax

     (function() { 'use strict'; angular .module('app', []) .controller('UserController', ['$scope', UserController]); function UserController($scope) { var self = this; // VARS // self.users = []; self.update = update; $scope.console = console; function update(user) { console.log('update->test'); return 'test'; } } })(); 
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.js"></script> <div ng-app="app"> <div ng-controller="UserController as UserController"> <a href="" ng-click="console.log('test')">Console.log('test')</a> <br/> <a href="" ng-click="UserController.update(user)">UserController.update(user)</a> </div> </div>