gpt4 book ai didi

javascript - 从嵌套指令调用 Controller 中的函数

转载 作者:行者123 更新时间:2023-11-29 22:05:43 25 4
gpt4 key购买 nike

我有两个嵌套指令用于在 Angular 中构建 TreeView :

父指令:

myApp.directive('nodes', function() {
return {
restrict: "E",
replace: true,
scope: {
nodes: '='
},
template: "<ul><node ng-repeat='node in nodes' node='node'></node></ul>"

}
});

子指令:

myApp.directive('node', function($compile) {
return {
restrict: "E",
replace: true,
scope: {
node: '='
},
template: "<li>{{node.ObjectName}}</li>",
link: function(scope, element, attrs) {
if (angular.isArray(scope.node.Children)) {

element.append("<nodes nodes='node.Children'></nodes>");

$compile('<nodes nodes="node.Children"></nodes>')(scope, function(cloned, scope) {

element.append(cloned);
});
}
}
}
});

Controller :

function myController($scope, DataService) {
$scope.init = function() {

DataService.getData(0, 0).then(function(data) {
$scope.treeNodes = $.parseJSON(data.d);
});
}

$scope.focusNode = function(prmNode) {
console.log(prmNode);
}

}

HTML:

<div ng-app="testTree" ng-controller="myController">
<div ng-init="init()">
<nodes nodes='treeNodes'></nodes>
</div>
</div>

我的问题是如何实现对 <li> 的点击哪个会调用 Controller 中的“focusNode”函数?

最佳答案

您可以通过属性传入函数。

Javascript

var myApp = angular.module('myApp', []);

myApp.directive('nodes', function() {
return {
restrict: "E",
replace: true,
scope: {
nodes: '=',
clickFn: '&'
},
template: "<ul><node ng-repeat='node in nodes' node='node' click-fn='clickFn()'></node></ul>"
}
});


myApp.directive('node', function($compile) {
return {
restrict: "E",
replace: true,
scope: {
node: '=',
clickFn: '&'
},
template: "<li><span ng-click='clickFn()(node)'>{{node.ObjectName}}</span></li>",
link: function(scope, element, attrs) {
if (angular.isArray(scope.node.Children)) {

element.append("<nodes nodes='node.Children' click-fn='clickFn()'></nodes>");

$compile('<nodes nodes="node.Children" click-fn="clickFn()"></nodes>')(scope, function(cloned, scope) {

element.append(cloned);
});
}
}
}
});

function myController($scope) {
$scope.focusNode = function(prmNode) {
console.log(prmNode);
}

$scope.root = {
ObjectName: 'Root',
Children:[{
ObjectName: 'A',
Children: [{
ObjectName: 'B'
}, {
ObjectName: 'C'
}]
}]
};
}

HTML

<!DOCTYPE html>
<html>

<head>
<script data-require="angular.js@*" data-semver="1.2.8" src="http://code.angularjs.org/1.2.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body ng-app='myApp' ng-controller="myController">
<node node="root" click-fn="focusNode"></node>
</body>

</html>

关于javascript - 从嵌套指令调用 Controller 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21088364/

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