【问题标题】:AngularJS Directive Two-Way Data Binding Not Working When Observing Boolean观察布尔值时AngularJS指令双向数据绑定不起作用
【发布时间】:2015-05-29 16:38:09
【问题描述】:

我有一个双向数据绑定,它不会改变发送到指令的变量的值。

我的指令监视触发器并将焦点放在 associates 元素上(基于在 SO 上找到的代码):

app.directive('focusMe', function ($timeout) {
  return {
    scope: {
      trigger: '=focusMe'
    },
    link: function (scope, element, attrs) {
      scope.$watch('trigger', function(value) {
        console.log("directive value: " + value);
        console.log("directive start: " + scope.trigger);
        if (value === true) {
          $timeout(function () {
            element[0].focus();
            scope.trigger = false;
            console.log("directive end: " + scope.trigger);
          });
        }
      });
    }
  }
});

在 HTML 中我这样称呼它:

<input type="text" ng-model="item.value" focus-me="focusInput" />

当我第一次触发它时,它就起作用了——因为focusInput 变量改变了它的值。但是当指令完成时,控制器范围内(指令之外)的focusInput 不会切换回false。

当我调用scope.trigger = false 时,应该会切换回false,假设我知道应该发生什么。

缺少什么会导致双向绑定不将值推回传递给指令的变量?

更新 01:

为了发布问题,我删除了一小段代码。 HTML 实际上是这样的:

<input type="text" ng-model="item.value" focus-me="focusInput" ng-if="item.condition != 'matches' && item.condition != 'does not match'" />

如果input 字段隐藏然后重新显示(基于ng-if),该指令将在focusInput 第一次更改时正确提供焦点。之后它将再次停止工作......除非重复隐藏/显示过程。

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    您遇到的问题是在作用域内处理原始值(布尔值、整数等)时的常见问题。

    我强烈建议阅读Understanding Scopes 文章。 (简短的回答:原语在指令的隔离范围内被更改,并且不会在父范围的链中向上搜索,即您的控制器范围)。

    至于如何解决您的情况,我建议使用点符号并将您的图元存储在一个对象中,并将该对象绑定到您的指令:

    scope: {
       triggerObj: '=focusMe'
    },
    

    并确保指令中的触发器引用现在是scope.triggerObj.trigger。

    在你的控制器中有:

    $scope.triggerObj = {};
    $scope.triggerObj.trigger = true; //or false, what have you
    

    拥有一个对象将确保双向绑定能够正常工作。有空的时候看看上面的文章:)

    【讨论】:

      【解决方案2】:

      指令创建范围。当您将参数传递给作用域时,对象通过引用传递,布尔值(以及数字、字符串...)通过值传递。

      例如:

      function changeToFalse(bool) {
          bool= false;
          console.log(bool);  // false
      }
      
      
      function changeObjToFalse(obj) {
          obj.bool= false;
          console.log(obj.bool);  // false
      }
      
      var obj = {bool : true};
      
      changeToFalse(obj.bool);
      console.log(obj.bool);  // true
      changeObjToFalse(obj);
      console.log(obj.bool); // false
      

      另请参阅相同的问题 - two way binding not working with ng-repeat。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多