Use ng-show on a custom replace directive does not show or hide

纵饮孤独 提交于 2019-12-11 11:21:22

问题


I am having an issue with getting ng-show (or ng-hide) to work on a custom directive. It is working just fine on normal HTML elements.

I made up a very simple example that shows the issue:

<div ng-app="appMod">
  <div ng-controller="Ctrl3">
      <button>First</button>
      <button ng-hide="NoSecond">Second</button>

      <mybutton ng-hide="NoSecond" label="My button"/>
  </div>
</div>  

and the JS:

function Ctrl3($scope) {
    $scope.NoSecond = true;
};

var appmod = angular.module('appMod', []);

appmod.directive("mybutton", function() {
    return {
        restrict: "E",
        template: "<div style='border: 1px solid black;'><button>{{label}}</button></div>",
        scope: {label:'@'}
    };
});

The end result is that the html button 'Second' is hidden, but 'mybutton' is not. http://jsfiddle.net/fotoguy42/4j7td/2/

How can I make the ng-hide/show work on my widget?


回答1:


Ok so this is actually mostly a duplicate of Why ng-hide doesn't work with custom directives?

Because you're creating a new scope in your directive you have to pass the variable noSecond to the directive and include it in the new scope.

Also - you should really use camelCase for your javascript:

JS:

function Ctrl3($scope) {
  $scope.noSecond = true;
};

var appmod = angular.module('appMod', []);

appmod.directive("mybutton", function() {
    return {
        restrict: "E",
        template: "<div style='border: 1px solid black;'><button>{{label}}</button></div>",
        scope: {label:'@', noSecond: '='}
    };
});

HTML:

<div ng-app="appMod">
  <div ng-controller="Ctrl3">
      <button>First</button>
      <button ng-hide="noSecond">Second</button>

      <mybutton ng-hide="noSecond" label="My button" no-second="noSecond"/>
  </div>
</div>    

It does appear that this has changed in angular 1.2.1 although I can't seem to find the change in the migration guide that would be responsible for this....

https://docs.angularjs.org/guide/migration



来源:https://stackoverflow.com/questions/23396103/use-ng-show-on-a-custom-replace-directive-does-not-show-or-hide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!