简体   繁体   中英

how to write a simple ng-show directive in angular js

I'm having trouble with the simple basics of angular directives and I was hoping for the most basic example of how to write an new ng-show directive. ie. I want to write directive ng-show2 to work the same as ng-show.

I get confused because in the angular.js file, the directive is defined like this:

var ngShowDirective = ngDirective(function(scope, element, attr){
  scope.$watch(attr.ngShow, function(value){
    element.css('display', toBoolean(value) ? '' : 'none');
  });
});

but then most of the directive examples I see are written like this:

var myApp = angular.module('myApp', []);
myApp.directive('ngShow2', function() {
    return {
        replace: true,
        restrict: 'A',
        link: function(){....}
});

​ what exactly is corresponding with what?

I'm not an expert on AngularJS internals, but what you are seeing[1] is a method angular uses to create directives internally. If you look at the ngDirective 's signature you'll notice is the same as the link function used in most examples.

During the built process the function ngShowDirective is added to the ng module. [2], and AFIK is not exposed.

Since what you want is a basic example of how to implement a ng-show directive, all you need to do is create a module for your app, and add the directive to that module, here's a simple example

App.directive('ngShow2', function() {
    return {
        replace: true,
        restrict: 'A',
        link: function(scope, element, attr){
            scope.$watch(attr.ngShow2, function(value){
               element.css('display', value ? '' : 'none');
            });
        }
    };
});

jsfiddle: http://jsfiddle.net/jaimem/L7QEE/


[1] https://github.com/angular/angular.js/blob/master/src/ng/directive/ngShowHide.js#L36-40

[2] https://github.com/angular/angular.js/blob/master/src/AngularPublic.js#L89

This code works as well

<!doctype html>
<html ng-app="myApp" ng-controller="AppCtrl">
<script src="js/angular.min.js"></script>
<body>
<h1 ng-show2="show" ng-bind="name"></h1>
</body>
</html>​

<script>
  var app = angular.module('myApp', []);

  app.controller('AppCtrl', function AppCtrl($scope){
    $scope.name = 'Guest';
    $scope.show = true;
  });

  app.directive('ngShow2', function(){
    return function($scope, $element, $attributes){
      var expr = $attributes.ngShow2;
      $element.css('display', $scope[expr] ? '' : 'none');
    };
  });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM