![](/img/trans.png)
[英]How to call AngularJS parent directive scope method from child directive
[英]How to call AngularJS JavaScript directive methods from the global scope
我有一個指令,類似於AngularJS的示例之一,如下所示。 如何從全局范圍調用toggle方法? 我希望能夠從一些舊代碼中切換zippy。
myApp.directive('zippy',
function(){
return {
restrict: 'E',
replace: true,
transclude: true,
scope: { title:'bind' },
template:
'<div class="zippy">' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {
var title = angular.element(element.children()[0]),
opened = true;
title.bind('click', toggle);
function toggle() {
opened = !opened;
element.removeClass(opened ? 'closed' : 'opened');
element.addClass(opened ? 'opened' : 'closed');
}
toggle();
}
}
});
當您想通過舊版訪問事件時,應使用angular的$ apply方法,如下所示:
function set_from_legacy(dom_element) {
var scope = angular.element(dom_element).scope();
scope.$apply(function() {
scope.viewmodel_element.property1 = something;
scope.viewmodel_element.property2 = somethingelse;
});
}
然后,angular應該加入並更新與視圖模型關聯的HTML中的屬性。
例如,稍微改變您的模板,使其具有綁定到控制器中模型zippy的className(當然可以是zippy的數組)
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.