我正在尝试使用 AngularJs 指令构建导航菜单。我正在使用 superfish jQuery 菜单插件。
它工作正常,除了 2 个问题。
- 一旦模型发生变化,jQuery 插件就会失败。
- 为了使插件工作,我必须在指令的“链接”方法中设置一个超时。这不是一个优雅的解决方案。
这是一个 jsFiddle:http: //jsfiddle.net/ashraffayad/xRB9u/
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.directive('navMenu', ['$parse', '$compile', function ($parse, $compile) {
return {
restrict: 'E', //Element
scope: true,
link: function (scope, element, attrs) {
scope.$watch(attrs.menuData, function (val) {
var template = angular.element('<ul class="sf-menu" id="parentTreeNavigation"><li ng-repeat="node in ' + attrs.menuData + '" ng-class="{active:node.active && node.active==true, \'has-dropdown\': !!node.children && node.children.length}"><a ng-href="{{node.href}}" >{{node.text}}</a><sub-navigation-tree></sub-navigation-tree></li></ul>');
var linkFunction = $compile(template);
linkFunction(scope);
element.html(null).append(template);
}, true);
setTimeout(function(){
$('.sf-menu').superfish();
},1000);
}
}
}]);
myApp.directive('subNavigationTree', ['$compile', function ($compile) {
return {
restrict: 'E', //Element
scope: true,
link: function (scope, element, attrs) {
scope.tree = scope.node;
if (scope.tree.children && scope.tree.children.length) {
var template = angular.element('<ul class="dropdown "><li ng-repeat="node in tree.childrehttp://jsfiddle.net/ashraffayad/TwZ25/#runn" node-id={{node.' + attrs.nodeId + '}} ng-class="{active:node.active && node.active==true, \'has-dropdown\': !!node.children && node.children.length}"><a ng-href="{{node.href}}" ng-click="{{node.click}}" target="{{node.target}}" ng-bind-html-unsafe="node.text"></a><sub-navigation-tree tree="node"></sub-navigation-tree></li></ul>');
var linkFunction = $compile(template);
linkFunction(scope);
element.replaceWith(template);
} else {
element.remove();
}
}
}
}]);
function MyCtrl($scope) {
$scope.changemodel = function(){
$scope.model[0].text = "some other text";
};
$scope.model = [
{"text":"someText", "href":""},
{"text":"someText", "href":""},
{"text":"someText", "href":"",
"children":[{}]
}
];
$scope.name = 'Superhero';
}
和html:
<div ng-controller="MyCtrl">Hello, {{name}}!
<button ng-click="changemodel()">change model</button>
<nav-menu menu-data="model"></nav-menu>
</div>
注意:由于某种原因,当我将子数组添加到模型时,jsFiddle 不喜欢它。但是这个例子在我的电脑上工作,没有 jsFiddle 上的错误。
谢谢你。