我正在尝试$观察指令范围内发生的更改,并在数组已更改时将对象添加到数组中。编辑功能在指令范围内,但保存功能在指令范围之外,即从控制器范围调用save。我正在使用共享对象进行双向绑定以访问已在指令范围内编辑的对象。正确保存了编辑但我需要过滤掉任何未更改的对象。我不明白为什么这些变化没有反映在$ watch中。
// controller
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>
答案 0 :(得分:2)
这看起来像是一种奇怪的方式,但我认为你只需要告诉你的手表观看INSIDE globalConfigs这样的对象:
$scope.$watch('vm.accessor.globalConfigs', function(newValue, oldValue) {
console.log('config changed');
},true);
注意$ watch&#34;,true&#34;的第三个参数。告诉观看&#34;深度观察&#34;。