【问题标题】:Why is this ng-show directive not working in a template?为什么这个 ng-show 指令在模板中不起作用?
【发布时间】:2013-10-20 20:47:14
【问题描述】:

我正在尝试编写一个指令,该指令将对元素进行简单的就地编辑。到目前为止,这是我的代码:

directive('clickEdit', function() {
return {
  restrict: 'A',
  template: '<span ng-show="inEdit"><input ng-model="editModel"/></span>' +
            '<span ng-show="!inEdit" ng-click="edit()">{{ editModel }}</span>',
  scope: {
    editModel: "=",
    inEdit: "@"
  },
  link: function(scope, element, attr) {
    scope.inEdit = false;
    var savedValue = scope.editModel;
    var input = element.find('input');

    input.bind('keyup', function(e) {
      if ( e.keyCode === 13 ) {
        scope.save();
      } else if ( e.keyCode === 27 ) {
        scope.cancel();
      }
    });

    scope.edit = function() {
      scope.inEdit = true;
      setTimeout(function(){
        input[0].focus();
        input[0].select();
      }, 0);
    };

    scope.save = function() {
      scope.inEdit = false;
    };

    scope.cancel = function() {
      scope.inEdit = false;
      scope.editModel = savedValue;
    };
  }
}
})

scope.edit 函数将 inEdit 设置为 true,并且效果很好 - 它隐藏了文本并显示了输入标签。但是,将 scope.inEdit 设置为 false 的 scope.save 函数根本不起作用。它不会隐藏输入标签并显示文本。

为什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您正在从对keyup 事件作出反应的事件处理程序中调用scope.save()。然而,这个事件处理程序不是由/通过 AngularJS 框架调用的。 AngularJS 只会扫描模型的更改,如果它认为可能已经发生更改以减少工作量(AngularJS 目前进行脏检查是计算密集型的)。

    因此,您必须利用scope.$apply 功能让AngularJS 知道您正在对范围进行更改。将 scope.save 函数更改为此,它应该可以工作:

    scope.save = function(){
      scope.$apply(function(){
        scope.inEdit = false;
      });
    });
    

    此外,似乎实际上不需要将此save 函数绑定到范围变量。因此,您可能希望改为定义一个“普通”函数,或者只是将代码集成到您的事件处理程序中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-17
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多