我有一個指令集中我的選擇的HTML和功能,但我有一個問題,ng-model在ng-change發生後正在更新。ng-change後更新的AngularJS範圍
這裏有一個集中的jsfiddle例如:
http://jsfiddle.net/U3pVM/1568/
(代碼,因爲SO否則抱怨)
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
改變:1,但真正:2
當你改變選擇到A,然後B.
這是更新但在ng-change被觸發後。
很顯然,我可以解決此通過傳遞ID(像我這樣做),或在該值時,控制器使用$手錶,但這是不理想的某些更復雜的情況。
任何想法?
是的,它的作品我也加NEWVALUE!==屬性oldValue :) – lunicon