“全球"AngularJS中ng-repeat中的变量 [英] "Global" variables in ng-repeat in AngularJS
问题描述
我正在创建一个Web应用程序,该应用程序通过 ng-repeat
'指令< make-dialog>
设置了多个对话框窗口.每个对话框的特定信息(宽度,高度,位置等)都存储在控制器中的数组中,并作为范围变量传递到指令中.
I am creating a web app that has multiple dialog windows set up by ng-repeat
'ing a directive, <make-dialog>
. Information specific to each dialog (width, height, position, etc), is stored in an array in the controller and passed into the directive as a scope variable.
现在,我想添加一个布尔范围变量,该变量可以被所有对话框窗口访问和修改.因此,当您在任何对话框中单击"+"按钮时,范围变量将更改为"true",而所有其他对话框都将识别出已进行了更改.
Now, I would like to add a boolean scope variable that can be accessed and modified by all the dialog windows. So when you click the "+" button in any of the dialogs, the scope variable changes to "true", and all the other dialogs recognize that that change has been made.
这是我尝试过的代码的草图:
Here is a sketch of the code I have tried:
控制器:
angular.module('root', [])
.controller('index', ['$scope', function($scope){
$scope.dialogs = [
{
minimized: false,
maximized: false,
width: 200,
height: 300,
top: 5,
left: 5,
zindex: 1,
template: 'experiment-dialog.html'
},
{
minimized: false,
maximized: false,
width: 200,
height: 250,
top: 257,
left: 238,
zindex: 0,
template: 'other-dialog.html'
}];
$scope.bool = false; //The variable I want to be able to access and change
}]);
指令:
.directive('makeDialog', function($document) {
return {
restrict: 'E',
scope: {
model: '=',
dialogs: '=',
bool: '='
},
template: "<button ng-click='maximize()> + </button>'",
link: function(scope, element, attrs) {
scope.maximize = function() {
scope.bool = true;
}
}
}
});
index.html:
index.html:
<html>
<body ng-app='root' ng-controller='index'>
<div id='container'>
<div ng-repeat='dialog in dialogs|filter:{minimized:false}'>
{{bool}}
<make-dialog model='dialog' dialogs='dialogs' bool='bool'></make-dialog>
</div>
</div>
</body>
</html>
这将在屏幕上显示两个按钮和文字假假".但是,当我单击"+"按钮之一时,只有一个的"false"值更改为true.因此,此变量不是全局变量,而是某种程度上只能通过一个对话框看到.有什么方法可以解决此问题,以便单击一个按钮将使两个对话框都意识到该变量现在为true?
This displays on the screen two buttons and the words "false false". But when I click one of the "+" buttons, only one of the "false" values changes to true. So this variable is not global, but is somehow only seen by one dialog. Is there any way to fix this, so that clicking on one button will make both dialogs realize that the variable is now true?
推荐答案
检查工作演示:柱塞
Your problem is that you bind the model to some primitive variable inside the ng-repeat
:
ngRepeat指令对集合中的每个项目实例化一次模板.每个模板实例都有自己的作用域
The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope
因此,请使用某些对象执行双向绑定.
So, use some object to perform the two-way binding.
这篇关于“全球"AngularJS中ng-repeat中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!