AngularJS – 在指令范围内设置变量
发布时间:2020-12-17 10:34:06 所属栏目:安全 来源:网络整理
导读:我正在尝试在$scope上设置一个变量selected.child,以便我可以在其他地方使用它.我仍然是Angular中范围的新手,但不确定为什么我不能在指令范围内设置范围.我可以调用范围函数. 我有一个JSfiddle,代码发布在下面. 我在这里先向您的帮助表示感谢. HTML: div ng
我正在尝试在$scope上设置一个变量selected.child,以便我可以在其他地方使用它.我仍然是Angular中范围的新手,但不确定为什么我不能在指令范围内设置范围.我可以调用范围函数.
我有一个JSfiddle,代码发布在下面. 我在这里先向您的帮助表示感谢. HTML: <div ng-controller="DashCtrl"> <h3>{{selected.child}}<h3> <div ng-repeat="child in children" select={{child}}> {{child.username}} </div> </div> 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" }; });
您错过了对$apply的调用
只需修改您的代码,如下所示 scope.selected.child = jQuery.parseJSON(attrs.select); //Neither this // scope.setSelected(jQuery.parseJSON(attrs.select)); //Nor this is working scope.$apply(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |