0
我试图$监视指令作用域中发生的更改,并将对象添加到数组(如果已更改)。编辑功能位于指令作用域中,但保存功能位于指令作用域之外,即从控制器作用域调用保存。我正在使用共享对象来使用双向绑定来访问已在指令作用域中编辑的对象。编辑被正确保存,但我需要筛选出任何未被更改的对象。我不明白为什么这些更改没有反映在$ watch中。Angular JS - 从控制器指令中进行的更改
//控制器
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>
谢谢,就是这样!你有任何改进代码的建议吗?我仍然不熟悉使用指令。 – neridaj
通常,如果我需要在我的控制器中有一个指令调用某个外部指令,我会将该函数作为参数传递给指令。这样,你可以在指令中使用$ watch,并在触发它时调用你传递给指令的函数。这有助于保持指令代码独立,因此您可以轻松地重新使用它。 – Scott