目前我正试图用角度来编写面包屑用于学习目的:)我等待$ routeChangeSuccess事件并填充名为crumb的数组。在面包屑的模板中使用ng-repeat读取此数组。我还想访问范围的变量。例子:
app.directive('breadCrumb', ['$location', '$route', '$routeParams', function(location, route, routeParams) {
return {
link: function($scope, element, attrs) {
$scope.$on('$routeChangeSuccess', function(next, current) {
var loc = location.path();
if(loc.indexOf('/users') >-1 && loc!='/users')
$scope.crumb= [{href:"/users",val:"Meine Kommilitonen"},
{href:"/users/"+current.params.id,val: current.params.id}];
});
},
template: '<div ng-bind="test"></div><div style="float:left" ng-repeat="item in crumb"><a href="{{item.href}}">{{item.val}}</a></div><div style="clear:both"></div>'
}
}])
这很好用。但现在我想推送像{href:current.params.id,val:$ scope.user.userName}这样的对象。这个值在控制器中,它加载路径的模板。如果我直接在模板中写出{{$ route.current.scope.users.userName}}就好了。
现在我如何将此值推送到数组,以便它绑定到div并将被解释为控制器的值。希望你能理解我的问题。
编辑:我已经搜索了很长时间了。我的需要是(我知道其他任何东西都不能用于我的目的),我需要像这样编译:&#39; {{route.current.scope.user.userName}}&#39;在linkfunction中的指令里面。答案 0 :(得分:0)
如果我理解正确,您的控制器中有一个值,并且您希望它在指令中可用吗?
可以通过属性(attrs)或双向数据绑定(范围)访问。我将展示双向绑定示例。
JS(指令):
app.directive('breadCrumb', ['$location', '$route', '$routeParams', function(location, route, routeParams) {
return {
// add scope
scope: {
myValue: "=" // = means two way binding (you could probably use @ for one way binding)
},
link: function(scope, element, attrs) {
console.log(scope.myValue); // the value on the directive
// yourArray.push(scope.myValue);
scope.$on('$routeChangeSuccess', function(next, current) {
var loc = location.path();
if(loc.indexOf('/users') >-1 && loc!='/users')
scope.crumb= [{href:"/users",val:"Meine Kommilitonen"},
{href:"/users/"+current.params.id,val: current.params.id}];
});
},
template: '<div ng-bind="test"></div><div style="float:left" ng-repeat="item in crumb"><a href="{{item.href}}">{{item.val}}</a></div><div style="clear:both"></div>'
}
}])
JS(控制器):
$scope.someValue = {
href: "/users",
val: 1
};
HTML:
<div bread-crumb my-value="someValue" ></div>
另一种方法是使用attrs,不需要范围,HTML是相同的
<div bread-crumb my-value="someValue" ></div>
JS:
app.directive('breadCrumb', ['$location', '$route', '$routeParams', function(location, route, routeParams) {
return {
link: function(scope, element, attrs) {
console.log(attrs.myValue); // the value on the directive
// yourArray.push(attrs.myValue);
scope.$on('$routeChangeSuccess', function(next, current) {
var loc = location.path();
if(loc.indexOf('/users') >-1 && loc!='/users')
scope.crumb= [{href:"/users",val:"Meine Kommilitonen"},
{href:"/users/"+current.params.id,val: current.params.id}];
});
},
template: '<div ng-bind="test"></div><div style="float:left" ng-repeat="item in crumb"><a href="{{item.href}}">{{item.val}}</a></div><div style="clear:both"></div>'
}
}])