javascript - 当指令更新相同的范围变量时, Angular 父范围不会更新

标签 javascript angularjs

我已经编写了一个指令来验证某些绑定(bind)值并在对按钮执行操作之前修改它。但是指令值中的任何值更新都不会反射(reflect)在父范围中。我在指令中使用了 (=),所以我假设它也会更新父作用域。

让我知道我做错了什么。已附上图片。

This is the view where both parent and the directive sharing the same text value.

The result value assigned to the validate text is not reflected in the parent selected node. while the ok function is executed. I have tried $timeout, $evalAsync on the scope.ngClick with no success. enter image description here

这是父级和指令共享相同文本值的 View 。

分配给验证文本的结果值不会反射(reflect)在父选定节点中。执行 ok 函数时。

我确实看到文本区域中的值得到更新。但是不知道为什么在执行ok函数的时候没有更新。

我在 scope.ngClick 上尝试了 $timeout、$evalAsync 但没有成功。

最佳答案

在自定义指令元素的事件处理程序内部所做的更改不会触发 Angular 的摘要循环。因此,您需要通知 Angular 范围已更改(通过调用 scope.$digest()scope.$apply())。我注意到的另一件事是方法 ok() 被调用了两次:一次在 Angular 的 ngClick 指令中,第二次在你的指令中。如果这不是所需的行为,请将其从您的指令中删除。这是一些工作代码:

HTML

<body ng-controller="myController">
  <textarea ng-model="selected.note"></textarea>
  <button type="button" validatetext="selected.note" ng-click="ok()">Click Me!</button>
</body>

JavaScript

angular.module('online-desktop', []).
  controller('myController', ['$scope', function($scope) {
    $scope.selected = {
      note: 'old value'
    };
    $scope.ok = function() {
      alert($scope.selected.note);
    };
  }]).
  directive('validatetext', [function() {
    return {
      scope: {
        validatetext: '='
      },
      link: function(scope, element, attr) {
        element.on('click', function() {
          scope.$apply(function() { // <= change scope properties inside scope.$apply()
            scope.validatetext = 'some new value';
          });
        });
      }
    }
  }]);

笨蛋:http://plnkr.co/edit/rmJVBzjIeiVcoQUV79z2?p=preview

关于javascript - 当指令更新相同的范围变量时, Angular 父范围不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021657/

相关文章:

javascript - 如何根据选中的复选框禁用文本框

javascript - Angular 2 和 C# API - 未处理的 Promise 拒绝 : ReferenceError: _body is not defined

javascript - 无法在 Angular js中获取该值

angularjs - AngularJS 中的范围未更新

javascript - 在 AngularJS 中将组件导入页面

javascript - 为我的应用程序提供服务时出现空白页面(Vue Router 4 - Vue 3)

javascript - 加载页面预加载器时隐藏滚动条

javascript - Angularjs 路由和 html5

javascript - 有没有可能异步调用 jquery .each 方法?

javascript - AngularJS 中隔离作用域指令和 $observer