Use ng-show on a custom replace directive does not

2019-10-20 01:24发布

我有越来越NG-秀(或NG隐藏)到自定义的指令工作的问题。 它工作正常的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"/>
  </div>
</div>  

和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:'@'}
    };
});

最终的结果是,HTML按钮“二”是隐藏的,但“myButton的”不是。 http://jsfiddle.net/fotoguy42/4j7td/2/

我怎样才能让我的插件的NG-隐藏/显示工作?

Answer 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



文章来源: Use ng-show on a custom replace directive does not show or hide