如何实现自定义指令的NG-变化 [英] How to implement an ng-change for a custom directive

查看:178
本文介绍了如何实现自定义指令的NG-变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板的指令就像

I have a directive with a template like

<div>
    <div ng-repeat="item in items" ng-click="updateModel(item)">
<div>

我的指令被声明为:

My directive is declared as:

return {
    templateUrl: '...',
    restrict: 'E',
    require: '^ngModel',
    scope: {
        items: '=',
        ngModel: '=',
        ngChange: '&'
    },
    link: function postLink(scope, element, attrs) 
    {
        scope.updateModel = function(item)
        {
             scope.ngModel = item;
             scope.ngChange();
        }
    }
}

我想,当点击一个项目,foo的值已经被改为呼吁NG-变化。

I would like to have ng-change called when an item is clicked and the value of foo has been changed already.

即,如果我的指令被实现为:

That is, if my directive is implemented as:

<my-directive items=items ng-model="foo" ng-change="bar(foo)"></my-directive>

我希望打电话给巴当foo的值已经更新。

I would expect to call bar when the value of foo has been updated.

使用上述code,ngChange调用成功,但它被称为以foo,而不是新的更新值的旧值。

With code given above, ngChange is successfully called, but it is called with the old value of foo instead of the new updated value.

要解决的问题的一个方法是调用ngChange超时内部在未来某一时刻,当foo的值已经被改变来执行它。但是,这种解决方案使了,一切事都应该被执行的顺序我失去控制,我认为应该有一个更好的解决方案。

One way to solve the problem is to call ngChange inside a timeout to execute it at some point in the future, when the value of foo has been already changed. But this solution make me loose control over the order in which things are supposed to be executed and I assume that there should be a more elegant solution.

我也可以在父范围内使用观察者过富,但这种方法并不能真正给被implmented的ngChange方法,我已被告知,观察是巨大的内存消耗。

I could also use a watcher over foo in the parent scope, but this solution doesn't really give an ngChange method to be implmented and I have been told that watchers are great memory consumers.

有没有一种方法,使ngChange在没有超时或观察家同步执行?

Is there a way to make ngChange be executed synchronously without a timeout or a watcher?

例如:<一href=\"http://plnkr.co/edit/8H6QDO8OYiOyOx8efhyJ?p=$p$pview\">http://plnkr.co/edit/8H6QDO8OYiOyOx8efhyJ?p=$p$pview

推荐答案

如果您需要ngModel你可以在ngModelController只是setViewValue $含蓄地评价NG-变化。第四个参数的链接功能应该是ngModelCtrl。下面code将使NG-变化工作的指令。

If you require ngModel you can just $setViewValue on ngModelController which implicitly evaluates ng-change. The fourth parameter to the linking function should be the ngModelCtrl. The following code will make ng-change work for your directive.

   link : function(scope, element, attrs, ctrl){
  scope.updateModel = function(item)
  {
    ctrl.$setViewValue(item);
  }
}

为了您的解决方案的工作,请从myDirective的分离范围删除ngChange和ngModel。

In order for your solution to work, please remove ngChange and ngModel from isolate scope of myDirective.

下面是一个普拉克: http://plnkr.co/edit/UefUzOo88MwOMkpgeX07?p = preVIEW

这篇关于如何实现自定义指令的NG-变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆