gpt4 book ai didi

javascript - 如何从页面 Controller 访问指令中的dom元素

转载 作者:行者123 更新时间:2023-11-29 15:35:01 25 4
gpt4 key购买 nike

我尝试访问指令中的元素,但我的 Controller 找不到它,怎么办?在下面的示例中, Controller MyCtrl 中的变量 Canvas 为空。

编辑:具体来说,我的指令是自定义折叠,因此其中的内容可以是多种多样的。例如,我有一个 View 显示由我的指令制作的那些折叠中的信息,用户可以编辑它。顺便说一句,业务逻辑在 View Controller 中,它处理数据加载和发送用户修改。下面的代码经过编辑以更加准确。

html:

<div ng-controller="MyCtrl">
<collapsible-div title="Open Me">
<canvas id="myCanvas"></span>
</collapsible-div>
</div>

Controller :

myApp.controller("MyCtrl",['$scope', function($scope) {

var canvas = document.getElementById('myCanvas');
/* Some code do draw image in my canvas... */

}]);

指令:

myApp.directive('collapsibleDiv', function(){
return {
restrict: 'E',
transclude: true,
replace: true,
scope: {
title: '@'
},
controller: function ($scope, $element) {
/* Some code to make my collapsible div how I want... */
/* This has nothing to deal with content, this directive can store any kind of content */
},
templateUrl: 'collapsible.html'
};
});

最终解决方案: Controller 不应该访问指令 dom,我可能会使用更模块化的方法使用新指令来处理我的 Canvas ,我的 html 现在看起来像这样,而我的 Controller 是空的:

<collapsible-div title="Open Me">
<my-canvas></my-canvas>
</collapsible-div>

最佳答案

我认为您在理解指令和 Controller 之间的区别时遇到了问题。我建议您更深入地了解这些概念。

关于您的特定问题,因为您正在使用指令,并且还因为您应该管理指令上的所有 DOM 操作,所以放置它的地方将是指令的链接功能。

在这种情况下,是这样的:

myApp.directive('directive', function(){
var directive = {
restrict: 'E',
transclude: true,
replace: true,
template: '<div ng-transclude></div>'
link : directiveLinkFunction
};

function directiveLinkFunction( scope, element, attrs ) {

// element -> the DOM element that hold the directive.
// for different selection, use the jQuery lite API

}

return directive;
});

然后您需要使用一些其他策略在 Controller 和指令之间共享数据,但那是一个完全不同的话题。

要点 -> 对指令执行所有 DOM 操作。

关于javascript - 如何从页面 Controller 访问指令中的dom元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com