标签归档:AngularJS

使用angularjs directive生成api方法供其他地方调用angularjs directive expose api

有些时候我们需要directive生成api,可以在其他地方(controller)调用
image1419911269
下面介绍下简单的步骤:

使用directive的双向绑定绑定controller里的变量

html:
<div expose="exposedApi"></div>
js:

directive('expose',function(){
  return {
    restrict: "A",
    scope: {
      api: "=expose"
    }
  };

这个时候controller离的exposedApi变量和directive里的api是双向绑定的

给directive里的api增加可调用的方法

directive('expose',function(){
  return {
    restrict: "A",
    scope: {
      api: "=expose"
    },
    controller: function($scope){
      $scope.number = 0;
      $scope.api={
        count:function(){
          $scope.number ++;
        }
      };
    },
    template: '<div class="well">' +
              '<p>count: {{number}}</p>' +
              '</div>'
  };

调用directive里的方法

controller("ctrl",function($scope){
  $scope.count = function(){
    $scope.exposedApi.count();
  };
})

Demo:

http://shengoo.github.io/angularjs-practice

完整代码:

<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.css" />
  <script src="../bower_components/angular/angular.js"></script>
</head>
<body ng-controller="ctrl">
<div class="container">
<div expose="exposedApi"></div>
<a ng-click="count()" class="btn btn-primary">click</a>
<div expose="exposedApi2"></div>
<a ng-click="count2()" class="btn btn-primary">click</a>
</div>
<script>
angular.module("app",[])
.controller("ctrl",function($scope){
  $scope.count = function(){
    $scope.exposedApi.count();
  };
  $scope.count2 = function(){
    $scope.exposedApi2.count();
  };
})
.directive('expose',function(){
  return {
    restrict: "A",
    scope: {
      api: "=expose"
    },
    controller: function($scope){
      $scope.number = 0;
      $scope.api={
        count:function(){
          $scope.number ++;
        }
      };
    },
    template: '<div class="well">' +
              '<p>count: {{number}}</p>' +
              '</div>'
  };
})
</script>
</body>
</html>

angularjs星级评分 star rating directive

directive

var app = angular.module("app", []);
app.controller('ctrl',function($scope){
  $scope.max = 5;
  $scope.ratingVal = 2;
  $scope.readonly = false;
  $scope.onHover = function(val){
    $scope.hoverVal = val;
  };
  $scope.onLeave = function(){
    $scope.hoverVal = null;
  }
  $scope.onChange = function(val){
    $scope.ratingVal = val;
  }
});
app.directive('star', function () {
  return {
    template: '<ul class="rating" ng-mouseleave="leave()">' +
        '<li ng-repeat="star in stars" ng-class="star" ng-click="click($index + 1)" ng-mouseover="over($index + 1)">' +
        '\u2605' +
        '</li>' +
        '</ul>',
    scope: {
      ratingValue: '=',
      max: '=',
      readonly: '@',
      onHover: '=',
      onLeave: '='
    },
    controller: function($scope){
      $scope.ratingValue = $scope.ratingValue || 0;
      $scope.max = $scope.max || 5;
      $scope.click = function(val){
        if ($scope.readonly && $scope.readonly === 'true') {
          return;
        }
        $scope.ratingValue = val;
      };
      $scope.over = function(val){
        $scope.onHover(val);
      };
      $scope.leave = function(){
        $scope.onLeave();
      }
    },
    link: function (scope, elem, attrs) {
      elem.css("text-align", "center");
      var updateStars = function () {
        scope.stars = [];
        for (var i = 0; i < scope.max; i++) {
          scope.stars.push({
            filled: i < scope.ratingValue
          });
        }
      };
      updateStars();
      scope.$watch('ratingValue', function (oldVal, newVal) {
        if (newVal) {
          updateStars();
        }
      });
      scope.$watch('max', function (oldVal, newVal) {
        if (newVal) {
          updateStars();
        }
      });
    }
  };
});

css:

.rating {
  color: #a9a9a9;
  margin: 0;
  padding: 0;
}
ul.rating {
  display: inline-block;
}
.rating li {
  list-style-type: none;
  display: inline-block;
  padding: 1px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
}
.rating .filled {
  color: #ffee33;
}

html:

<div ng-app="app">
<div class="well" ng-controller="ctrl">
  <div star rating-value="ratingVal" max="max" on-hover="onHover" on-leave="onLeave" readonly="{{readonly}}"></div>
  <div>
    Max: <input type="number" name="input" ng-model="max" min="0" max="99" required>
    <p>current value: {{ratingVal}}</p>
    <p>hover on : {{hoverVal?hoverVal:"none"}}</p>
    <p>readonly : <input type="checkbox"
       ng-model="readonly"></p>
  </div>
</div>
</div>

github page

http://shengoo.github.io/angularjs-practice/directive/star/star.html

jsfiddle:

code pen:

See the Pen angularjs star rating directive by Qing Sheng (@shengoo) on CodePen.

AngularJs分页pagination directive

html

<div ng-app="hello">
    <div ng-controller="pagingCtrl">
        <paging>
            <table class="table table-striped table-bordered table-hover">
                <tr>
                    <th>id</th>
                    <th>name</th>
                </tr>
                <tr ng-repeat="item in data">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                </tr>
            </table>
            <ul class="pagination" num-pages="tasks.pageCount" current-page="tasks.currentPage" on-select-page="selectPage(page)">
                <li ng-class="{disabled: noPrevious()}"> <a ng-click="selectPrevious()">&laquo;</a>
                </li>
                <li ng-repeat="page in pages" ng-class="{active: isActive(page)}"> <a ng-click="selectPage(page)">{{page}}</a>
                </li>
                <li ng-class="{disabled: noNext()}"> <a ng-click="selectNext()">&raquo;</a>
                </li>
            </ul>
        </paging>
    </div>
</div>

js

var myModule = angular.module('hello', []);
myModule.controller('pagingCtrl', function ($scope, $http) {
    $scope.data = [{
        id: 1,
        name: "a"
    }, {
        id: 2,
        name: "b"
    }];
    $scope.currentPage = 1;
    $scope.numPages = 5;
    $scope.pageSize = 10;
    $scope.pages = [];
    //get first page
    /*$http.get('url',
                {
                    method: 'GET',
                    params: {
                        'pageNo': $scope.currentPage,
                        'pageSize': $scope.pageSize
                    },
                    responseType: "json"
                }).then(function (result) {
                    $scope.data = result.data.Data;
                    $scope.numPages = Math.ceil(result.data.Total / result.data.PageSize);
                });*/
    $scope.onSelectPage = function (page) {
        //replace your real data
        /*$http.get('url',
                {
                    method: 'GET',
                    params: {
                        'pageNo': page,
                        'pageSize': $scope.pageSize
                    },
                    responseType: "json"
                }).then(function (result) {
                    $scope.data = result.data.Data;
                    $scope.numPages = Math.ceil(result.data.Total / result.data.PageSize);
                });*/
    };
});
myModule.directive('paging', function () {
    return {
        restrict: 'E',
        //scope: {
        //    numPages: '=',
        //    currentPage: '=',
        //    onSelectPage: '&'
        //},
        template: '',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch('numPages', function (value) {
                scope.pages = [];
                for (var i = 1; i <= value; i++) {
                    scope.pages.push(i);
                }
                alert(scope.currentPage)
                if (scope.currentPage > value) {
                    scope.selectPage(value);
                }
            });
            scope.isActive = function (page) {
                return scope.currentPage === page;
            };
            scope.selectPage = function (page) {
                if (!scope.isActive(page)) {
                    scope.currentPage = page;
                    scope.onSelectPage(page);
                }
            };
            scope.selectPrevious = function () {
                if (!scope.noPrevious()) {
                    scope.selectPage(scope.currentPage - 1);
                }
            };
            scope.selectNext = function () {
                if (!scope.noNext()) {
                    scope.selectPage(scope.currentPage + 1);
                }
            };
            scope.noPrevious = function () {
                return scope.currentPage == 1;
            };
            scope.noNext = function () {
                return scope.currentPage == scope.numPages;
            };
        }
    };
});

jsfiddle