在 AngularJS 中使用 controllerAs 语法时,为 ng-click 等定义处理程序的最佳位置是什么?在控制器上还是在作用域上(在链接函数中定义)?
那么,您是否使用:
angular.module('app', []).
    controller('myDirective', function(){
        return {
            template: '<div><button ng-click=vm.onClick()></button></div>',
            controller: function(){
                var vm = this;
                vm.onClick = function(){
                    vm.myValue = vm.doSomethingFancy();
                };
                this.doSomethingFancy = function(){};
            }
        }
    });
或者:
angular.module('app', []).
    controller('myDirective', function () {
        return {
            template: '<div><button ng-click=onClick()></button></div>',
            require: 'myDirecive',
            controller: function () {
                var vm = this;
                this.doSomethingFancy = function () {
                    vm.myValue = 'somethingfancy';
                };
            },
            link: function (scope, elem, attr, ctrl) {
                scope.onClick = function () {
                    ctrl.doSomethingFancy();
                }
            }
        }
    });
我实际上喜欢第二个,因为现在控制器只分配值并且事件处理是在链接函数中完成的。
无论如何......让我知道你的想法是什么。