我正在尝试使用AngularJs指令构建导航菜单。我正在使用superfish jQuery菜单插件。
除2个问题外,它的工作正常。
这是一个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>
注意:由于某些原因,当我将children数组添加到模型时,jsFiddle不喜欢它。但是这个例子就像在我的电脑上一样,没有jsFiddle上的错误。
谢谢。
答案 0 :(得分:1)
我想我喜欢挑战:
你的小提琴有一堆问题。来自记忆:
scope: true
隔离,那么您需要从某个地方获取数据(例如$ rootScope,$ scope。$ parent或某些服务)。我改变了你的范围,以便它通过你的指令所关心的项目。menuData
,而不是试图将它连接成一个像你一样的对象,无论如何都不会有效......它等同于{{ 1}}