angularJS如何使用参数$ eval函数

时间:2015-03-31 09:52:13

标签: angularjs

我正在尝试实现该指令,在指令中,我想要$ eval包含函数名和参数值的值:

Html页面:

<select mydirective="action('pValue')">

AngularJS指令代码:

app.directive('mydirective', function ($timeout) {
return {
    restrict: 'A',
    link: function ($scope, element, attr) {
            $timeout(function () {
                $scope.$eval(attr.mydirective);
        });
    }
}

我期望的是它将调用范围中的动作函数define并将pValue作为函数参数传递。我怎么能让它工作呢?

2 个答案:

答案 0 :(得分:3)

你想要自动发生什么,函数会用值调用,这就是eval的目的:

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.action = function(val) {
    alert(val);
  }

});

app.directive('mydirective', function($timeout) {
  return {
    restrict: 'A',
    link: function($scope, element, attr) {

      $timeout(function() {
        $scope.$eval(attr.mydirective);
      });
    }
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MainCtrl">
  <select mydirective="action('pValue')"></select>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

对于那些寻找将$ event信息传递给自定义指令方法的人,请参阅下面的示例:

<强> TEMPLATE:

<div on-touch-end="onTouchEnd( 'some data' )">
   TOUCH ME!
</div>

<强>控制器:

$scope.onTouchEnd = function( data ) {
    console.log("onTouchEnd event with data", data, event );
};

<强>指令:

.directive('onTouchEnd', function() {
    return {
        restrict    : 'A',
        link        : function( $scope, $element, $attr ) {
            $element.on('touchend', function( event ) {
                $scope.$apply(function() {
                    $scope.$eval( $attr.onTouchEnd );
                });
            });
        }
    }
})