我正在尝试制作一个从两个输入源读取的指令,并做一些事情将其变成一个。所以要做到这一点,我正在听我的两个输入的变化并将新的组合值分配给我的指令的 ngModel。
问题是我还需要知道何时在指令之外修改 ngModel 以执行相反的过程并正确设置我的两个指令输入源的值。有正确的方法吗?
我做了一个片段来更好地说明问题,这不是我的实际指令。
angular.module('myapp', [])
.controller('AppController', function($scope, $timeout) {
$scope.data = {
value: ''
};
$timeout(function() {
$scope.data.value = 'hellooooo';
}, 5000);
})
.directive('sampleDirective', function() {
return {
require: 'ngModel',
restrict: 'E',
template: '<input ng-model="data.input1" ng-change="changed()"><input ng-model="data.input2" ng-change="changed()">',
scope: {
ngModel: '='
},
controller: function($scope) {
$scope.data = {};
$scope.changed = function() {
$scope.ngModel = $scope.data.input1 + ' + ' + $scope.data.input2;
}
// The watch is running even when the ngModel is modified inside the changed function above
// I want it to only run when the model is changed from outside the directive, like
// I'm doing in the AppController.
$scope.$watch('ngModel', function(value) {
if (value) {
// Just simulating some processing
var length = value.length;
$scope.data.input1 = value.slice(0, length/2);
$scope.data.input2 = value.slice(length/2, length-1);
}
});
}
};
});
<div ng-app="myapp">
<div ng-controller="AppController">
<sample-directive ng-model="data.value"></sample-directive>
<br>
<br>
<div>{{ data.value }}</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.js"></script>