3

将一个函数传递给init指向一个指令,该函数通过字符串属性进行标记,然后被解析并使用。这个问题在使用时,函数绑定不再附加/绑定到函数所属的对象上。这里是我的意思(see on plunker带有原始绑定的指令中的函数回调

<html ng-app="plunker"> 

<head> 
<script data-require="[email protected]" src="http://code.angularjs.org/1.2.13/angular.js" data-semver="1.2.13"></script> 
<script> 
var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.container = { 
    x: null 
    , setup: function(x){ 
     console.log(this); //this here should be $scope.container, but its window 
     this.x = x; 
    } 
    }; 
}); 

app.directive('dir', ['$parse', function($parse) { 
    return { 
    restrict: 'E' 
    , transclude: false 
    , scope: true 
    , link: function(scope, element, attrs) { 
     var callback = attrs.setup 
     , someCalcVar = 10 
     ; 
     $parse(callback)(scope)(someCalcVar); 
    } 
    }; 
}]); 

</script> 
</head> 

<body ng-controller="MainCtrl"> 
    <p>container.x == '{{container.x}}'</p> 
    <dir setup="container.setup"></dir> 
</body> 

</html> 

有没有办法实现我想要什么?也许有更好的方法来设计这个,但仍然保留回调和相关变量的某种容器?

编辑:

一个天真的胜利可能是检查是否回调有dot然后将它绑定使用func.bind(substr(callback, ...))手动...是有什么内建于角,将做到这一点?或者有更清晰的方法来处理这一切?

+0

也许这样的事情? http://plnkr.co/edit/S461ZpcWXX2wq0AIQx2n?p=preview –

+0

@AlexandrinRus与问题是指令必须知道'容器'这不是它通常需要知道/强制执行 – Pykler

+0

为了简单win,使用ng-init。刚才说的ng-init =“container.setup()” –

回答

1

这还不是最完美的解决方案,但你总是可以只创建一个可在容器包装了呼吁建立一个功能:

$scope.callableSetup = function(x) { 
    $scope.container.setup(x); 
} 
+0

这是有效的,这是事实,但正如你所说,不是最优雅的。仍然支持一些非常好的东西:) – Pykler

1

尝试:

var that = this; 
$scope.container = { 
    x: null, 
    setup: function(x) { 
     console.log(that); //this here should be $scope.container, but its window 
     console.log(x); 
     that.x = x; 
    } 
}; 
+1

不应该'that = $ scope.container'而不是'this'? – Pykler

+0

这是控制器,它是一个参考 – Whisher