我有指令'copyPaste‘,它将元素值复制到'destination’属性中指定的元素。
// html code
<div ng-app='app'>
<div ng-controller="mainController">
<input type='text' ng-model='firstInput' copy-paste destination='secondInput'>
<input type='text' ng-model='secondInput'>
<!-- following does not work -->
<input type='text' ng-model='param.firstInput' copy-paste destination='param.secondInput'>
<input type='text' ng-model='param.secondInput'>
</div>
</div>
//directive code
module.directive('copyPaste',['$rootScope',function($rootScope){
return {
restrict:'A',
link:function(scope,element,attrs,ctrl){
var destination=attrs.destination;
scope.$watch(attrs.ngModel, function (v) {
scope[destination]=v
});
}
}
}])
//controller
module.controller('mainController',['$scope',function($scope){
$scope.firstInput='hello'
}]);如果我传递简单的变量,上面的代码就可以工作。如果我传递object,array,它就不起作用了。如何将数组和对象作为字符串传递给指令,然后作为变量使用。我不想在isolate作用域中运行指令,在isolate作用域中,我需要调用$scope.$apply来更新绑定,所以要尽量避免使用isolate作用域。
发布于 2017-03-23 17:53:37
好的,我让它起作用了。这应该能做到这一点,参见-> plunk:
基本上,我遍历您的作用域树来查找您想要为其设置值的对象。不是最漂亮的,但它能完成工作
var module = angular.module('app', []);
module.directive('copyPaste', ['$rootScope', function($rootScope) {
return {
restrict: 'A',
link: function(scope, element, attrs, ctrl) {
var destination = attrs.destination;
scope.$watch(attrs.ngModel, function(v) {
var splitted = destination.split('.');
if (splitted.length > 1) {
var value = null;
var lastKey = "";
for (var i = 0; i < splitted.length; i++) {
if(value == null) {
value = scope[splitted[i]];
} else {
if(value[typeof splitted[i] == 'Object']) {
value = value[splitted[i]];
} else {
lastKey = splitted[i];
}
}
}
value[lastKey] = v;
} else {
scope[destination] = v;
}
});
}
}
}])
module.controller('mainController', ['$scope', function($scope) {
$scope.firstInput = 'hello';
$scope.secondInput = "";
$scope.param = {};
$scope.param.secondInput = "";
$scope.param.firstInput = "Again";
}]);发布于 2017-03-23 16:55:42
您可以使用JSON.stringify将值转换为JSON字符串,然后使用JSON.parse将JSON文本字符串转换为Javascript对象
发布于 2017-03-23 17:02:28
我认为你应该使用事件而不是$watch,它的性能会更好。看看ngChange (https://docs.angularjs.org/api/ng/directive/ngChange)
我认为问题可能是由于$watch没有正确检查您的变量。
您可以尝试将objectEquality布尔值设置为true (此处为https://docs.angularjs.org/api/ng/type/$rootScope.Scope文档)
scope.$watch(attrs.ngModel, function (v) {
scope[destination]=v
}, true); // <-- deep object checkhttps://stackoverflow.com/questions/42971123
复制相似问题