我正在尝试 $watch 指令范围内发生的更改,如果对象已更改,则将其添加到数组中。编辑功能在指令范围内,但保存功能在指令范围之外,即从控制器范围调用保存。我正在使用共享对象以两种方式绑定来访问已在指令范围内编辑的对象。编辑已正确保存,但我需要过滤掉任何未更改的对象。我不明白为什么这些更改没有反映在 $watch 中。
// 控制器
vm.accessor = {};
getGlobalConfigs();
$scope.$watch('vm.accessor.globalConfigs', function(newValue, oldValue) {
console.log('config changed');
});
function getGlobalConfigs() {
vehicleConfigurationsFactory.getGlobalConfigs()
.then(function (data) {
vm.accessor.globalConfigs = data;
});
}
// 指令
(function(){
'use strict';
angular.module('vehicleConfigurationsModule')
.directive('globalConfig', globalConfig);
function globalConfig() {
var directive = {
link: link,
replace: false,
templateUrl: 'app/vehicle-configurations/global-config-tr.html',
scope: {
confkey: '@',
confvalue: '=',
confprecedence: '=',
confdescription: '=',
accessor: '='
}
}
return directive;
function link(scope, el, attrs, controller) {
scope.master = {
confvalue: scope.confvalue,
confprecedence: scope.confprecedence,
confdescription: scope.confdescription
};
scope.disabled = true;
scope.precedenceOptions = [
{value: "GLOBAL"},
{value: "VEHICLE"}
];
scope.selectedOption = {value: scope.confprecedence};
scope.edit = function() {
scope.disabled = false;
scope.accessor.disabled = false;
};
scope.cancel = function() {
scope.disabled = true;
scope.accessor.disabled = true;
scope.confvalue = scope.master.confvalue;
scope.confprecedence = scope.master.confprecedence;
scope.confdescription = scope.master.confdescription;
};
scope.setPrecedence = function(value) {
scope.confprecedence = value;
};
}
}
})();
// 指令实例
<tr ng-repeat="config in vm.accessor.globalConfigs" global-config confkey="{{ config.confKey }}" confvalue="config.confValue" confprecedence="config.precedence" confdescription="config.description" accessor="vm.accessor"></tr>
// 指令模板
<td ng-model="config.confKey">{{ confkey }}</td>
<td>
<input type="text" class="form-control" ng-model="confvalue" ng-disabled="disabled">
</td>
<td>
<select class="form-control" ng-options="option.value for option in precedenceOptions track by option.value"
ng-model="selectedOption" ng-disabled="disabled" ng-change="setPrecedence(selectedOption.value)"></select>
</td>
<td>
<input type="text" class="form-control" ng-model="confdescription" ng-disabled="disabled">
</td>
<td>
<a ng-show="disabled" role="button" translate="{{ 'vehicle-configurations.edit' }}" ng-click="edit()"></a>
<a ng-show="!disabled" role="button" translate="{{ 'vehicle-configurations.cancel' }}" ng-click="cancel()"></a>
</td>