Javascript 将对象(变量)传递给指令angularjs
在状态中调用控制器Javascript 将对象(变量)传递给指令angularjs,javascript,angularjs,Javascript,Angularjs,在状态中调用控制器 .controller('test', function($scope) { $scope.variable = 'Hello'; $scope.other = 'Hi'; }) .directive('customDir', function() { return { restrict: 'A', link: function($scope, element, attrs) { attrs.cu
.controller('test', function($scope) {
$scope.variable = 'Hello';
$scope.other = 'Hi';
})
.directive('customDir', function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
attrs.customDir += ' Word';
}
}
});
{{variable}}
{{其他}}
我需要$scope.variable和$scope.other接收“Word”,必须能够更改指令中传递的变量的值。方法很少。第一种是使用双向绑定:
.directive('customDir', function() {
return {
scope: {customDir: '='},
link: function(scope, element, attrs) {
scope.customDir += ' Word';
}
}
});
演示:
如果不需要新的隔离作用域,请选择另一个:
.directive('customDir', function() {
return {
link: function(scope, element, attrs) {
scope[attrs.customDir] += ' Word';
}
}
});
演示:方法很少。第一种是使用双向绑定:
.directive('customDir', function() {
return {
scope: {customDir: '='},
link: function(scope, element, attrs) {
scope.customDir += ' Word';
}
}
});
演示:
如果不需要新的隔离作用域,请选择另一个:
.directive('customDir', function() {
return {
link: function(scope, element, attrs) {
scope[attrs.customDir] += ' Word';
}
}
});
演示:您希望指令能够更改外部变量吗?您是在询问一个指令,该指令根据输入框中输入的内容更改变量吗?@CShark事实上,我弄错了一个示例,应该在指令中输入一个“更改”“。但我想要的很简单,我需要更改指令中的外部变量。你想让指令能够更改外部变量吗?你是在问一个指令,它只是根据输入框中键入的内容更改变量吗?@CShark事实上,我弄错了示例,应该在指令中加上一个‘更改’“。但我想要的很简单,我需要更改指令中的外部变量。第二种方法的问题是如果
attrs.customDir
是“model.variable”,而不仅仅是“variable”。我的意思是scope['variable']
有效,但scope['model.variable']
无效。我用您的第二个plunkr创建了一个版本,该版本将使用$parse
处理这种情况@dfsq完美!!只需在作用域变量(customDir)中添加$timeout,因为它总是传递上一个值。第二种方法的问题是,如果attrs.customDir
是“model.variable”而不仅仅是“variable”,该怎么办。我的意思是scope['variable']
有效,但scope['model.variable']
无效。我用您的第二个plunkr创建了一个版本,该版本将使用$parse
处理这种情况@dfsq完美!!只需在范围变量(customDir)中放入$timeout,因为它总是传递上一个值。