繁体   English   中英

ui路由器和指令的范围问题

[英]Scope issue with ui-router and directives

我知道以前曾提出过类似的问题,并且已经解决了很多问题,但是作为初学者,我仍然无法使我的代码正常工作。 这里有一个小矮人。 我的最终目标是为我可能要在不同页面上使用的模板的键盘快捷方式设置一个“侦听器”。 在“输入”时,它应该处理输入,但不会。 单击按钮可以正常工作。

我的身体看起来很轻松:

<body ng-controller="BoxController as box" ng-keyup="box.checkKey($event)">
  <div ui-view="content"></div>
</body>

我的app.js

(function() {
  var app = angular.module('boxApp', ['ui.router']);

  app.config(['$stateProvider', '$urlRouterProvider',
    function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/');

      $stateProvider
        .state('app', {
          url: '/',
          views: {
            'content': {
              template: '<my-box></my-box>',
              controller: 'BoxController as box'
            }
          }
        })
    }
  ]); 

  app.controller('BoxController', function($scope) {
    $scope.userEntry = {txt: 'ye'};

    this.checkInput = function() {
      if ($scope.userEntry.txt == "yeah") { alert("Bingo!"); } 
      else alert("Uh oh: " + $scope.userEntry.txt);
    };

    this.checkKey = function(keyEvent) {
      if (keyEvent.which == 13) { this.checkInput(); }
    };
  });

  app.directive('myBox', function() {
    return {
      restrict: 'E',
      template: '<input type="text" ng-model="userEntry.txt"><button ng-click="box.checkInput()"> Check </button>',
    };
  });

})();

我确定我有一些作用域访问问题,但我自己无法解决。 另外:我怀疑将checkKey放在一种主控制器上,而不将BoxController包括在正文的所有页面上是有意义的。 任何帮助将不胜感激。 先感谢您!

我会在指令中进行所有这些操作以保持关注点分离。

app.directive('myBox', function() {
  return {
    restrict: 'E',
    template: '<input type="text" ng-model="userEntry.txt"><button ng-click="checkInput()"> Check </button>',
    controller: function($scope, $document){

      $scope.userEntry = {
        txt: ''
      };

      $document.bind('keydown keypress', function(event){
        if(event.which === 13) {
         $scope.checkInput(); 
        }
      });

      $scope.checkInput = function() {
        if ($scope.userEntry.txt == "yeah") {
          alert("Bingo!");
        } else alert("Uh oh: " + $scope.userEntry.txt);
      };
    }
  };
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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