簡體   English   中英

AngularJS自定義指令ng-show / ng-hide

[英]AngularJS custom directive ng-show/ng-hide

警告:Angular新手提前。

我正在嘗試創建一個自定義窗口小部件,默認情況下會顯示“回復”鏈接,單擊時,應該隱藏它,並顯示textarea。 這是我到目前為止,但它不起作用::

  .directive('replybox', function ($rootScope) {
    var linkFn = function (scope, element, attrs) {
        var label = angular.element(element.children()[0]);
        scope.showInput = false;

        label.bind("click", textbox);

        function textbox() {
            scope.showInput = true;
        }
    };
    return {
        link:linkFn,
        restrict:'E',
        scope:{
            id:'@',
            label:'@',
            showInput:'='
        },
        template:'<a ng-hide="showInput">label</a><textarea ng-show="showInput">    </textarea>',
        transclude:true
    };
})

任何指南將不勝感激。 謝謝!

Matias,這是一個有用的jsFiddle: http//jsfiddle.net/pkozlowski_opensource/Z6RzD/

實際上有很多事情發生,但我認為最重要的事情是你需要使用Scope。$ apply以從“anular的世界之外”改變角度通知范圍。 默認情況下,angular不會觸發模板重新評估每個DOM事件,因此您需要將其包裝到apply中:

scope.$apply('showInput = true');

更多信息:http://docs.angularjs.org/api/ng.$ro​​otScope.Scope

您的示例中還有其他值得注意的項目:

  • 我想您希望能夠將'label'作為屬性傳遞給您的指令,然后在模板中使用它 - 如果是這樣,您需要使用{{label}}表達式
  • 我不太確定'id'屬性的用途是什么,所以從我的小提琴中省略了它
  • 對於'showInput'也是如此 - 無法弄清楚你想要獲得的東西是什么

你也可以使用$ timeout來通知你的變化角度,例如

.directive('replybox', function($rootScope, $timeout) {
  var linkFn = function(scope, element, attrs) {
    var label = angular.element(element.children()[0]);
    scope.showInput = false;

    label.bind("click", textbox);

   function textbox() {
     $timeout(function() {
       scope.showInput = true;
     });

   }
 };
 return {
  link: linkFn,
  restrict: 'E',
  scope: {
    id: '@',
    label: '@',
    showInput: '='
  },
  template: '<a ng-hide="showInput">label</a><textarea ng-show="showInput">    </textarea>',
  transclude: true
 };
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM