所以我有这个指令叫说, mySave
,这是pretty的简单,只是这个
So I have this directive called say, mySave
, it's pretty much just this
app.directive('mySave', function($http) {
return function(scope, element, attrs) {
element.bind("click", function() {
$http.post('/save', scope.data).success(returnedData) {
// callback defined on my utils service here
// user defined callback here, from my-save-callback perhaps?
}
});
}
});
元素本身看起来像这样
the element itself looks like this
<button my-save my-save-callback="callbackFunctionInController()">save</button>
callbackFunctionInController是现在只是
callbackFunctionInController is for now just
$scope.callbackFunctionInController = function() {
alert("callback");
}
当我的console.log()
attrs.mySaveCallback
我保存指令里面,它只是给了我一个字符串 callbackFunctionInController()
,我读地方我应该$解析这一点,那将是很好,所以我试图 $解析(attrs.mySaveCallback)
这给我回了一些功能,但几乎没有了一个我一直在寻找,它给我回
when I console.log()
attrs.mySaveCallback
inside my-save directive, it just gives me a string callbackFunctionInController()
, I read somewhere that I should $parse this and it would be fine, so I tried to $parse(attrs.mySaveCallback)
which gave me back some function, but hardly the one I was looking for, it gave me back
function (a,b){return m(a,b)}
我是什么做错了吗?难道这种做法有缺陷的,从一开始?
What am I doing wrong? Is this approach flawed from the beginning?
那么,什么似乎是最好的办法是使用隔离的范围所建议的ProLoser
So what seems like the best way is using the isolated scope as suggested by ProLoser
app.directive('mySave', function($http) {
return {
scope: {
callback: '&mySaveCallback'
}
link: function(scope, element, attrs) {
element.on("click", function() {
$http.post('/save', scope.$parent.data).success(returnedData) {
// callback defined on my utils service here
scope.callback(); // fires alert
}
});
}
}
});
有关参数传递回控制器做到这一点
for passing parameters back to controller do this
[11:28] <revolunet> you have to send named parameters
[11:28] <revolunet> eg my-attr="callback(a, b)"
[11:29] <revolunet> in the directive: scope.callbak({a:xxx, b:yyy})