我有一个运行良好的网页,但在某个路线上,它不会加载某些功能。例如,这是代码:
myApp.controller('people', ['$scope', function($scope) {
$scope.$watch('$viewContentLoaded', function(){
console.log('la 1');
$scope.allPeople = function() {
// This does not run when refreshed at https://www.website.com/people
console.log('la 2');
}
})
]);
这具有相同的行为,la 1
有效,而不是la 2
:
myApp.controller('people', ['$scope', function($scope) {
console.log('la 1');
$scope.allPeople = function() {
console.log('la 2');
}
}]);
这些是路线:
myApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '../../templates/all.html',
controller: 'all'
})
.when('/people', {
templateUrl: '../../templates/people.html',
controller: 'people'
})
});
当我加载https://www.website.com
并导航到People
标签时,它会加载人员列表。但是,当我在People
标签中加载页面WHILE时,页面会加载,但没有列表:我看到la 1
已打印,而不是la 2
。
如何在从allPeople
刷新时运行/people
?
答案 0 :(得分:1)
原因是您只声明了该函数但从未执行过它。
myApp.controller('people', ['$scope', function($scope) {
$scope.allPeople = function() {
console.log('la 2');
}
$scope.$watch('$viewContentLoaded', function(){
console.log('la 1');
$scope.allPeople();
});
]);
此外,每次路线时都不要申报。 并且不要忘记取消注册手表(感谢@NainishModi)。
myApp.controller('people', ['$scope', function($scope) {
$scope.allPeople = $scope.allPeople || function() {
console.log('la 2');
}
var deReg = $scope.$watch('$viewContentLoaded', function(){
console.log('la 1');
$scope.allPeople();
})
//deRegister watch
$scope.$on('$destroy', deReg);
]);