angularjs - 如何从指令中调用 Controller 函数?

标签 angularjs angularjs-scope angular-ui angular-ui-bootstrap

如何从指令中调用 Controller 函数?或者如何从 Controller 访问指令 ng-model? 例如。我使用 angular ui bootstrap 时间组件,当时间改变时我需要通知 Controller 中的调用函数。 我认为一般来说,这是组件之间双向通信的典型用例。

appControllers.controller('mainCtrl', ['$scope', 
  function($scope) {

    $scope.changedTime = function(time) {
        alert(time);        
    }

 }]).directive('timePicker',['$http', function($http) {
  return {
    restrict: 'AE',    
    templateUrl: 'partials/time-picker.html',
    scope: true,
    controller: 'TimepickerDemoCtrl'        
  };
}]);


//partials/time-picker.html:
<span ng-controller="TimepickerDemoCtrl">              
   <timepicker ng-model="mytime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></timepicker>              
</span>


//TimepickerDemoCtrl (copy from source):
var TimepickerDemoCtrl = function ($scope) {
  $scope.mytime = new Date();
  $scope.hstep = 1;
  $scope.mstep = 15;

  $scope.options = {
    hstep: [1, 2, 3],
    mstep: [1, 5, 10, 15, 25, 30]
  };

  $scope.ismeridian = true;
  $scope.toggleMode = function() {
    $scope.ismeridian = ! $scope.ismeridian;
  };

  $scope.update = function() {       
    var d = new Date();
    d.setHours( 14 );
    d.setMinutes( 0 );
    $scope.mytime = d;
  };

  $scope.changed = function () {
    console.log('Time changed to: ' + $scope.mytime);
  };

};

最佳答案

这是一个框架应用程序,它演示了如何在使用隔离作用域时从指令调用父 Controller 函数以避免紧耦合(这增强了可重用性):

JS:

angular.module('myApp', [])
.controller('MyController', function($scope){
  $scope.showAlert = function(value){
    alert('Called from directive: ' + value);
  };
})
.directive('myDirective', function(){
  return {
    restrict: 'E',
    scope: {
      alert: '&'
    },
    controller: function($scope){
      $scope.value = 'directive scope value';
    },
    template: '<button ng-click="alert({message: value})">Alert</button>'
  }
});

HTML:

<body ng-app="myApp" ng-controller="MyController">
  <my-directive alert="showAlert(message)"></my-directive>
</body>

Plunker using this code

要关注的是在指令的 scope: { ... } 设置中使用 & 符号。在这种情况下,它使您能够在 HTML 指令声明的 alert 属性中命名 Controller 函数。

然后可以从指令的模板调用该函数。

在学习 Angular 中的指令时,使用隔离作用域是一个常见的痛点,但值得花时间思考一下。

特别是关于 & 的使用,我发现了 this video尤其有帮助。

关于angularjs - 如何从指令中调用 Controller 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23636727/

相关文章:

javascript - angularjs ui-select-choices 下拉字母顺序取决于给定的输入

javascript - 需要从 Angular JS UI 执行 Shell 脚本

angularjs - 当选定的 ng-option 更改时获取值

javascript - Angular 范围不打印变量

javascript - 如何获取 ng-repeat 上对象属性的项目计数

javascript - 切换月份和行显示时的 ui-calendar 问题

javascript - 当用户输入时如何获取 $viewValue 中的字符串?

javascript - “中央”删除前确认或JS中的多个版本

angularjs - 有什么方法可以将变量名与字符串连接起来,或者这是基本的编程错误

AngularJS : $q -> deferred API order of things (lifecycle) AND who invokes digest?