我需要从指令内的回调中修改根范围属性。但是,该指令位于由switch指令创建的内部范围内。
HTML
<div ng-app="app" ng-controller='AppController'> <p>Selected: {{ selected }}</p> <div ng-switch on="selected"> <div ng-switch-default> <p>Item: {{ selected }}</p> <custom-tag selected-item="selected" /> </div> <div ng-switch-when="New value"> <p>Worked</p> </div> </div> </div>
JavaScript
angular.module('app', []) .directive("customTag", [function () { return { restrict: "E", replace: true, template: "<input type='button' value='Click me' />", link: function (scope, element, attrs) { element.bind('click', function () { scope[attrs.selectedItem] = "New value"; scope.$apply(); }); } }; }]); function AppController($scope) { $scope.selected = 'Old value'; }
小提琴:http://jsfiddle.net/nJ7FQ/
我的目标是能够在“选定区域”中显示“新值”。我该如何完成我想做的事情?我究竟做错了什么?
此外,我正在尝试制作一个组件。有没有办法做到这一点,但要隔离范围?
我更新了小提琴,基本上不得不去父级来获取正确的“选定”变量,还使用了isolate scope =来获得传入的值和内部模型之间的双向绑定。
http://jsfiddle.net/nJ7FQ/2/
angular.module('app', []) .directive("customTag", [function () { return { restrict: "E", replace: true, template: "<input type='button' value='Click me' />", scope: {model:'='}, link: function (scope, element, attrs) { element.bind('click', function () { scope.model[attrs.selectedItem] = "New value"; scope.$apply(); }); } }; }]); function AppController($scope) { $scope.selected = 'Old value'; }
<div ng-app="app" ng-controller='AppController'> <p>Selected: {{ selected }}</p> <div ng-switch on="selected"> <div ng-switch-default> <p>Item: {{ selected }}</p> <custom-tag selected-item="selected" model="$parent" /> </div> <div ng-switch-when="New value"> <p>Worked</p> </div> </div> </div>
更新了jsfiddle以使用属性中的原始读取属性:http ://jsfiddle.net/nJ7FQ/4/