AngularJS范围NG-更改后更新 [英] AngularJS scope updated after ng-change

查看:112
本文介绍了AngularJS范围NG-更改后更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我集中了选择HTML和功能指令,但我在这里NG-发生变化后,NG-模型更新的问题。

I have a directive that centralises my select HTML and functionality but I have an issue where the ng-model is updating after ng-change happens.

下面是一个集中的jsfiddle例如:

Here's a focused jsfiddle example:

http://jsfiddle.net/U3pVM/1568/

(code,因为这么抱怨其他方式)

(Code because SO complains otherwise)

HTML

<div ng-app="myApp">    
    <div ng-controller="MainCtrl">
        <p>fooId is currently : {{fooId}}</p>

        <app-drop-down model="fooId" options="fooOptions" opt-value="id" opt-label="label" on-change="dropDownChanged"></app-drop-down>
    </div>
</div>

JS:

var app = angular.module('myApp', []);

app.controller('MainCtrl', function ($scope, $log) {
    $scope.fooId = -1;

    $scope.fooOptions = [{
        id: 1,
        label: "A"
    }, {
        id: 2,
        label: "B"
    }];

    $scope.dropDownChanged = function (id) {
        $log.info('changed : ' + $scope.fooId + ' but really: ' + id);
    };
});

app.directive('appDropDown', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            model: '=',
            options: '=',
            onChange: '='
        },
        template:
            '<div><select ng-model="model" ng-options="a[optValue] as a[optLabel] for a in options" ng-change="changed()"></select></div>',
        link: function (scope, element, attrs) {
            scope.optValue = attrs.optValue;
            scope.optLabel = attrs.optLabel;

            scope.changed = function () {
                scope.onChange(scope.model);
            };
        }
    };
});

控制台日志:

改变:-1但真正:1

changed : -1 but really: 1

改变:1,但真正:2

changed : 1 but really: 2

当你改变选择到A,然后到B。

When you change the select to A, then to B.

据更新,但NG-变化触发后。

It is updating but after the ng-change is triggered.

很显然,我可以解决此通过传递ID(像我一样),或在值时,控制器使用$手表,但这是不理想的某些更加复杂的场景。

Obviously, I can work around this by passing the id (like I do) or using $watch in the controller on the value but this isn't ideal for certain more complex scenarios.

任何想法?

推荐答案

包装你回调超时,像这样

Wrap your callback in a timeout, something like this

  scope.changed = function () {          
      $timeout(function() {
          scope.onChange(scope.model);
      });
  }; 

这篇关于AngularJS范围NG-更改后更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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