我的服务 NavData
angular.module('navData', []).
factory('NavData', function() {
var navData = {};
navData.depth = 0;
navData.category_id = "";
navData.category_name = "";
navData.subcategory_id = "";
navData.subcategory_name = "";
return navData;
});
在某些页面上从 ui-router 接收值:
var category = {
name: 'category',
parent: site,
url: '/categories/:category_id',
onEnter: function(NavData, $stateParams){
NavData.depth = 1;
NavData.category_id = $stateParams.category_id;
console.log(NavData);
},
views: {
'navigation': {
templateUrl: 'partials/category-menu.html'
},
'content': {
templateUrl: 'partials/category-images.html'
}
}
};
出现在所有页面上的指令应注意服务中的更改并将它们反映在自定义面包屑功能中:
.directive('breadcrumb', ['NavData', function(NavData){
return {
templateUrl: 'partials/breadcrumb.html',
link: function(scope, elm, attrs, ctrl){
scope.depth = NavData.depth;
scope.category_id = NavData.category_id;
scope.category_name = NavData.category_name;
scope.subcategory_name = NavData.subcategory_name;
var doStuff = function(navdata){
console.log("watching depth: " + navdata.depth);
console.log("watching cat_id: "+ navdata.category_id);
};
scope.$watch(NavData.depth, doStuff(NavData), true);
scope.$watch(NavData.category_id, doStuff(NavData), true);
}
};
}])
但是, scope.$watch 似乎不起作用。这是我的日志:
watching depth: 0 directives.js:28
watching cat_id: directives.js:29
watching depth: 0 directives.js:28
watching cat_id: directives.js:29
Object {depth: 1, category_id: "1", category_name: "", subcategory_id: "", subcategory_name: ""} app.js:25
我究竟做错了什么?