@H_301_6@
有问题的指令是这里的人:
Dynamic template in directive based on attributes?
Dynamic template in directive based on attributes?
无论如何,这就是我想要完成的事情.
这个< titlebar>指令可以采用名为edit-button的属性.如果存在,并且单击该按钮时,我想在我的控制器中设置一个$scope变量,该变量将切换按钮的可见性以删除/编辑项目.
例如,如果我设置$scope.currentlyEditting = true;在我的指令中,我将它绑定到控制器,然后使用ng-show来显示/隐藏控件.我只是不确定如何将数据存入我的控制器.
titleBar指令:
robus.directive("titlebar",function() { return { restrict: "E",template: "<header class='bar-title' ng-class='{\"sub-view\": view}'>"+ "<a class='button' ng-click='goBack()' ng-show='back'><i class='icon-arrow-left'></i> Back</a>" + "<h1 class='title' ng-transclude>" + "<span class='sub-title' ng-show='view'>{{view}}</span></h1>" + "<a class='button' ng-click='showEdit()' ng-show='edit'>Edit</a>" + "</header>",scope: { view: '@view',edit: '@editButton',back: '@backButton' },transclude: true,replace: true,link: function ($scope,$element,attrs,ctrl) { // $scope.$apply(); },controller: function($scope,$attrs,$location,$routeParams) { /* simple back button implementation */ $scope.goBack = function() { history.back(-1) } // $scope.showEdit = function() { // $scope.currentlyEditting = true; // } } } });
解决方法
您有几种方法可以完成此任务.
您可以使用$scope.$eval(attrs.editButton)(或view或backButton)来处理指令中的属性,而不是创建隔离范围.然后,您可以在您工作的任何范围内设置变量和调用函数.
如果您想继续使用隔离范围,您还可以使用&传递函数.这可以切换编辑模式.
这将是这样做的:
// In the directive template: '...<a href="" ng-click="toggleEdit()">Edit</a>...',scope: { ... toggleEdit: '&',... } // In the HTML (or directive template) <titlebar ... toggle-edit="toggleEditMode()" ...>...</titlebar> // In the controller (ngController,not directive controller) $scope.toggleEditMode = function() { $scope.editMode = !$scope.editMode; }
最后,您还可以使用$scope.$parent从指令中的隔离范围访问父作用域.我不建议这样做,因为它会在指令和控制器之间产生紧密耦合,但它是一个选项.