将一个函数传递给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, ...))
手动...是有什么内建于角,将做到这一点?或者有更清晰的方法来处理这一切?
也许这样的事情? http://plnkr.co/edit/S461ZpcWXX2wq0AIQx2n?p=preview –
@AlexandrinRus与问题是指令必须知道'容器'这不是它通常需要知道/强制执行 – Pykler
为了简单win,使用ng-init。刚才说的ng-init =“container.setup()” –