如何使用select和button创建指令

时间:2014-07-09 14:06:45

标签: javascript angularjs angularjs-directive

我创建了一个指令,该指令应该能够在控制器中调用函数并在控制器和指令中使用变量。

  • 我无法弄清楚如何调用回调。
  • 我无法想象在我的指令范围变量上启用双向数据绑定。

这是plnk:http://plnkr.co/edit/T1bMYUnkPeZmHHd05SCI?p=preview

的HTML

<!DOCTYPE html>
<html data-ng-app="App">
  <head>
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body data-ng-controller="BodyCtrl">
    <h1>{{title}}</h1>

    <div class="container">
      <div class="dateselector" data-ng-select="select" data-ng-refresh="refresh()"></div>
    </div>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.13/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.13/angular-route.min.js"></script>
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
  </body>

</html>

html模板

<div class="row">
  <div class="col-md-3 col-sm-3">
    <select class="form-control" ng-model="select" ng-options="p for p in possibilities"></select>
  </div>
  <div class="col-md-3 col-sm-3">
    <button type="button" class="btn btn-default">Refresh</button>
  </div>
</div>

的javascript

var app = angular.module('App', ['ui.select']);

app.controller('BodyCtrl', ['$scope', function($scope) {
  $scope.title = 'Select Directive';

  $scope.select = 1;

  $scope.refresh = function() {
    alert("Refresh in Controller! " + $scope.select);  
  };
}]);


// Module
angular.module('ui.select', [])
.directive('dateselector', ['$parse', function($parse) {
  var link = function ($scope, $element, $attributes) {
    $scope.possibilities = [1,2,3,4,5,6];

    $element.find('button').bind('click', function() {
      alert('Refresh in directive!');
      // How to call callback?
      $scope.refresh;
    });
  };

  return {
    restrict: 'EC',
        replace: true,
        templateUrl: 'template.html',
        scope: {
            select: "=",
            refresh: "&"
        },
        link: link
  };
}]);

1 个答案:

答案 0 :(得分:1)

基本问题是,您的指令希望查看some-namedata-some-name表单的属性,但您可以指定如下:data-ng-some-name

此外,将回调绑定到按钮的点击事件的推荐方法是使用ngClick

<!-- In the VIEW -->
<div class="dateselector" data-select="select" data-refresh="refresh()"></div>

<!-- In the TEMPLATE -->
<button ... ng-click="refresh()">Refresh</button>

另请参阅此 modified demo