![](/img/trans.png)
[英]Angular UI Datepicker Isn't Receiving Updated Scope Variable In Dates-Disabled Function
[英]Scope function isn't receiving a callback argument
我有一個像這樣的控制器:
angular.module('main', []).controller('mainCtrl', function ($scope) {
$scope.doStuff = function (cb) {
// Do some stuff.
cb();
};
});
我有這樣的指示:
angular.module('action-bar', []).directive('actionBar', function () {
return {
restrict: 'EA',
replace: true,
template: '<h1>test</h1>',
scope: {
doStuff: '&'
},
link: function (scope, element, attrs) {
scope.doStuff(function () {
alert('callback executed');
});
}
};
});
這是標記:
<div ng-app="main">
<div ng-controller="mainCtrl">
<div ng-action-bar></div>
</div>
</div>
我可以調用doStuff
,但是cb
參數總是undefined
即使我傳入一個匿名函數作為回調。 我在這做錯了什么?
將隔離范圍更改為使用=
而不是&
允許您訪問父范圍doStuff方法。
angular.module('main', ['action-bar']).controller('mainCtrl', function ($scope) {
$scope.doStuff = function (cb) {
// Do some stuff.
cb();
};
});
angular.module('action-bar', []).directive('actionBar', function () {
return {
restrict: 'EA',
replace: true,
template: '<h1>test</h1>',
scope: {
doStuff: '='
},
link: function (scope, element, attrs) {
scope.doStuff(function () {
alert('callback executed');
});
}
};
});
在您的標記中使用該指令
<div ng-app="main" ng-controller="mainCtrl">
<action-bar do-stuff="doStuff">
</action-bar>
</div>
這是一個有效的例子 。
如果你想使用表達式('&')語法將doStuff傳遞給你的指令,那么在你的html中你應該像這樣傳遞它:
<div action-bar doStuff="doStuff(cb)"></div>
在你的指令的鏈接函數中,你可以像這樣調用它:
scope.doStuff({cb: function() { ... }});
查看egghead.io視頻,了解更多信息: https ://egghead.io/lessons/angularjs-isolate-scope-expression-binding
注意:我個人不喜歡這種語法,所以我總是使用Jonathan Palumbo的解決方案(雙向綁定)。
我通過簡單地使用scope.$parent
來訪問父作用域來解決這個問題。 我實際上並不需要將父函數作為指令的隔離范圍的一部分。
例:
var app = angular.module('app', []);
// Main controller.
app.controller('mainCtrl', function ($scope) {
// Initial text added to log.
$scope.logs = ['App loaded.'];
// A log function to add additional lines to the log.
$scope.log = function (text, callback) {
$scope.logs.push(text);
if (callback) callback();
};
});
// Directive to log lines to the log viewer.
app.directive('ngLogLine', function () {
return {
restrict: 'E',
template: '<div><input type="text" ng-model="msg" ng-keydown="$event.keyCode === 13 ? log() : null" /><button ng-click="log()">send</button></div>',
replace: true,
scope: {},
link: function (scope, element, attrs) {
// Create our own log function on our isolate scope.
scope.log = function () {
// Call parent log function and pass in a callback.
scope.$parent.log(scope.msg, function () {
// Clear the msg, clearing the input.
scope.msg = '';
});
};
}
};
});
Codepen: http ://codepen.io/Chevex/pen/eHuaK/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.