<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.3" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="MainController as main">
<input ng-model="main.pasteValue"/> <button ng-click="main.paste()">paste</button>
<ul>
<li ng-repeat="value in main.values">
<input ng-model="value.v" twice /> {{value.v}}
</li>
</ul>
<ul>
<li ng-repeat="value in main.values">
<input ng-model="value.v" twice set-view="value.i"/> {{value.i}}({{value.v}})
</li>
</ul>
<ul id="values">
<li ng-repeat="value in main.values2">
<input ng-model="value.v" twice /> {{value.v}}
</li>
</ul>
</body>
</html>
angular.module('app', [])
.controller('MainController', MainController)
.directive('twice', twice)
.directive('setView', setView);
MainController.$inject = ['$scope']
function MainController($scope) {
this.values = [
{v: 1}, {v: 2}, {v: 3}
];
this.values2 = [
{v: 1}, {v: 2}, {v: 3}
];
this.pasteValue = 42;
this.paste = function() {
var value = this.pasteValue;
// 1
this.values.forEach(function(v) { v.i = value });
// 2
var inputs = angular.element(document.getElementById('values')).find('input');
angular.forEach(inputs, function(input) {
var ngModel = angular.element(input).controller('ngModel');
ngModel.$setViewValue(value);
input.value = value;
});
};
}
function twice() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
ngModel.$formatters.push(function(x) { return 2 * x });
ngModel.$parsers.push(function(x) { return 0.5 * x });
}
}
}
function setView() {
return {
require: 'ngModel',
scope: {
setView : '='
},
link: function(scope, elem, attr, ngModel) {
scope.$watch('setView', function(newValue) {
if (angular.isDefined(newValue)) {
elem.val(newValue);
ngModel.$setViewValue(newValue);
}
})
}
}
}