我想要做這樣的事情,如 fiddle,使文本消失並隨着每次點擊而重新出現。ng-show無法在指令模板中工作
問題是,在隔離範圍內,您似乎無法訪問控制器範圍。我解決了它的連接功能,處理有點擊事件,並使用範圍設置,我的「SHOWME」標誌$適用,如:
scope.$apply('showMe = false');
這是正確的方式去還是有一些更優雅的方法?
我想要做這樣的事情,如 fiddle,使文本消失並隨着每次點擊而重新出現。ng-show無法在指令模板中工作
問題是,在隔離範圍內,您似乎無法訪問控制器範圍。我解決了它的連接功能,處理有點擊事件,並使用範圍設置,我的「SHOWME」標誌$適用,如:
scope.$apply('showMe = false');
這是正確的方式去還是有一些更優雅的方法?
在這裏你去(http://jsfiddle.net/66d0t7k0/1/)
把你的點擊處理程序的鏈接功能和揭露showMe
到scope
app.directive('example', function() {
return {
restrict: 'E',
template: '<p ng-show=\"showMe\">Text to show</p><button ng-click=\"clickMe()\">Click me</button>',
scope: {
exampleAttr: '@'
},
link: function (scope) {
scope.clickMe = function() {
scope.showMe = !scope.showMe;
};
}
};
});
要擴大apairet的答案,因爲你的指令,可使用孤立的範圍,你可以處理模板本身的所有內容,如下所示:
app.directive('example', function() {
return {
restrict: 'E',
template: '<p ng-show=\"showMe\">Text to show</p><button ng-init=\"showMe = false\" ng-click=\"showMe = !showMe\">Click me</button>',
scope: {
exampleAttr: '@'
},
link: function (scope) {
}
};
});
另一個考慮因素是使用ng-if而不是ng-show,因爲它不會在DOM中呈現元素,直到表達式求值爲true。
您可以通過設置範圍躲在指令範圍:假 然後你可以把你所有的功能在主控制器範圍
angular.module('appMyApp').directive('appMyAppItem', function() {
return {
transclude: true,
templateUrl: 'link/to/url',
controller: 'appMyAppController',
scope: false
}
});
angular.module('appMyApp').controller('appMyAppController', ['$scope', function($scope){
$scope.showItem = true;
$scope.toggleItem = function(){
$scope.showItem = !$scope.showItem;
};
}]);
希望這有助於