AngularJS-在指令的作用域上设置变量
我试图在AngularJS-在指令的作用域上设置变量,angularjs,angularjs-directive,angularjs-scope,angularjs-ng-repeat,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Ng Repeat,我试图在$scope上设置一个变量selected.child,以便在其他地方使用它。我仍然不熟悉Angular中的作用域,但不确定为什么不能在指令中对作用域进行设置。我可以调用范围函数 我有一个为它和代码张贴在下面 提前谢谢你的帮助 HTML: <div ng-controller="DashCtrl"> <h3>{{selected.child}}<h3> <div ng-repeat="child in children" sel
$scope
上设置一个变量selected.child
,以便在其他地方使用它。我仍然不熟悉Angular中的作用域,但不确定为什么不能在指令中对作用域进行设置。我可以调用范围函数
我有一个为它和代码张贴在下面
提前谢谢你的帮助
HTML:
<div ng-controller="DashCtrl">
<h3>{{selected.child}}<h3>
<div ng-repeat="child in children" select={{child}}>
{{child.username}}
</div>
</div>
{{selected.child}
{{child.username}
javascript:
var dash = angular.module('dash', []);
dash.directive('select', function () {
return {
restrict: "A",
scope: false,
link: function (scope, element, attrs) {
element.bind('click', function () {
scope.selected.child = jQuery.parseJSON(attrs.select); //Neither this
scope.setSelected(jQuery.parseJSON(attrs.select)); //Nor this is working
if (attrs.select != scope.selected) {
other_elements = angular.element(document.querySelectorAll('[select]'));
for (var i = 0; i < other_elements.length; i++) {
elm = jQuery(other_elements[i]);
elm.css('background', 'none');
}
element.css('background', '#F3E2A9');
}
});
}
};
});
dash.controller('DashCtrl', function ($scope) {
$scope.setSelected = function (child) {
$scope.selected.child = child;
};
$scope.children = [{
"age_group": "6-8",
"username": "my_child"
}, {
"age_group": "8-10",
"username": "another_child"
}];
$scope.selected = {
child: "none"
};
});
var-dash=angular.module('dash',[]);
指令('select',函数(){
返回{
限制:“A”,
范围:假,
链接:函数(范围、元素、属性){
元素绑定('单击',函数(){
scope.selected.child=jQuery.parseJSON(attrs.select);//这两者都不是
scope.setSelected(jQuery.parseJSON(attrs.select));//这也不起作用
如果(attrs.select!=scope.selected){
其他元素=angular.element(document.querySelectorAll('[select]');
对于(var i=0;i<其他元素.length;i++){
elm=jQuery(其他_元素[i]);
css('background','none');
}
css('background','#F3E2A9');
}
});
}
};
});
dash.controller('DashCtrl',函数($scope){
$scope.setSelected=函数(子函数){
$scope.selected.child=child;
};
$scope.children=[{
“年龄组”:“6-8岁”,
“用户名”:“我的孩子”
}, {
“年龄组”:“8-10岁”,
“用户名”:“另一个孩子”
}];
$scope.selected={
孩子:“没有”
};
});
您缺少对$apply的调用
只需修改您的代码如下
scope.selected.child = jQuery.parseJSON(attrs.select); //Neither this
// scope.setSelected(jQuery.parseJSON(attrs.select)); //Nor this is working
scope.$apply();