var app = angular.module('app', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope, $modal, $q) {
$scope.confirm = function(newVal, oldVal){
if(newVal === 'black'){
return $modal.open({templateUrl:'confirm'}).result;
}
var dfd = $q.defer();
dfd.resolve();
return dfd.promise;
};
});
app.directive("deferChange", function(){
return{
restrict: 'A',
require: 'ngModel',
scope: {
viewModel: '=ngModel',
model: '=deferChangeDelegate',
defer: '&deferChange'
},
link: function(scope, el, attrs, ctrl){
function updateModel(){
scope.model = ctrl.$modelValue;
}
function updateViewModel(){
scope.viewModel = scope.model;
}
ctrl.$viewChangeListeners.push(function(){
scope.defer().then(updateModel, updateViewModel);
});
scope.$watch('model', updateViewModel);
}
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>Defer Change</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" data-semver="3.1.1" data-require="bootstrap-css@*" />
<link rel="stylesheet" href="style.css">
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js" data-require="angular.js@1.2.x"></script>
<script data-require="ui-bootstrap@*" data-semver="0.10.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1>Defer Model Change</h1>
<p>Try to select 'black' from the drop down, it will prompt to ask for confirmation, whereas using the button won't.</p>
<select class="form-control"
ng-model="sView"
defer-change-delegate="s"
defer-change="confirm(sView, s)"
ng-options="s for s in ['red','black','green']">
</select>
<button class="btn btn-primary" ng-click="s = 'black'">set as black via model (no prompt)</button>
<div ng-if="s == 'black'" class='blackbox'>
I'm black!
</div>
<script type="text/ng-template" id="confirm">
<div class="modal-body">
Are you sure?
<button class="btn btn-primary" ng-click="$close()">Yes</button>
<button class="btn btn-secondary" ng-click="$dismiss()">No</button>
</div>
</script>
</body>
</html>
.blackbox{
background-color:black;
color:white;
width:10em;
margin:1em 0;
padding:1em;
}
select.form-control{
display: inline-block;
width: auto;
}
body{
margin: 1em;
}