javascript - AngularJS 指令 : '&' in isolated scope isn't working as expected

标签 javascript angularjs

我正在尝试将方法从 Controller 传递到我的指令中。我就是这样做的:

在 Controller 中:

$scope.getEmployees = function()
{
    return {2: 'Jane', 3: 'Bob', 4: 'Smith'};
}

$scope.getSelected = function()
{
    return 3;
}

在 View /HTML 中:

<mydirective data-placeHolder="Choose an employee.." 
       data-getOpts="getEmployees()" data-getSelected="getSelected()" />

在指令中:

var dir = 
{
   restrict: 'E',
   templateUrl : 'views/mydirective.html',
   scope: {
       placeholder: '@',
       getSelected: '&',
       getOpts: '&'
   },   
   controller: ['$scope', '$element', '$attrs', 
       function($scope, $element, $attrs)
       {
           console.log( $scope.getOpts() );
       }],

};

MyApp.directive('mydirective', function()
 {
     return dir;
 });

但是,指令 Controller 中的以下行:

   console.log( $scope.getOpts() );

产生 undefined 而不是返回 Controller 的 getEmployees() 函数中设置的对象或函数。

我做错了什么?

最佳答案

这与命名约定有关。您需要将驼峰式大小写转换为破折号分隔的单词,如下所示

data-get-opts="getEmployees()" 

关于javascript - AngularJS 指令 : '&' in isolated scope isn't working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18371467/

相关文章:

javascript - 动态改变弹出窗口的位置

javascript - 如何关闭网页上指定输入字段的 iPhone 小键盘

ng-repeat 内部解析的 Javascript 语句行为不正确

javascript - 我怎样才能使一些表格行在 SmartTable angularjs 中不可选择

javascript - 为什么要使用 toString() 来对可以使用 typeof 检查的参数进行类型检查?

javascript - CSS 过渡持续时间不适用于过渡效果的第一个实例

javascript - 未捕获的语法错误 : Unexpected string - in my Angular function's return

javascript - 防止 Angular 每秒绑定(bind)

javascript - 在jquery中查找关联数组最大值的索引

javascript - 谷歌地图标记不显示