当我使用控制器作为语法时,ng-enter不起作用

时间:2016-12-30 11:55:14

标签: angularjs angularjs-directive angularjs-scope

我正在尝试在我的角应用中使用ngEnter指令

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

当我在没有控制器的情况下使用它作为语法时,它可以正常工作。

工作代码:

<div ng-app="NgEnterApp">
    <div ng-controller="NgEnterController">
        <input ng-enter="onEnterKey()" ng-model="MyText"/>
    </div>
</div>

<script>
    var $scope;
    var app = angular.module('NgEnterApp', []).controller('NgEnterController', NgEnterController);

    function NgEnterController($scope) {
        $scope.onEnterKey = function () {
            alert('hello ng-enter');
        };
    }
</script>

现在,在下一步中,我将NgEnterController更改为控制器,而ng-enter不起作用。

<div ng-app="NgEnterApp">
    <div ng-controller="NgEnterController as controller">
        <input ng-enter="controller.onEnterKey()" ng-model="MyText"/>
    </div>
</div>

<script>
    var $scope;
    var app = angular.module('NgEnterApp', []).controller('NgEnterController', NgEnterController);

    NgEnterController.$inject = ['$scope'];

    function NgEnterController($scope) {
        var controller = this;
        controller.onEnterKey = function () {
            alert('hello ng-enter');
        };
    }
</script>

0 个答案:

没有答案