run方法中执行了一个http请求来获取数据:
BlogApp.run(['$rootScope', '$http',
function($rootScope, $http) {
$http({
method: 'GET',
url: 'http://localhost:3000/posttag'
}).then(function(response) {
//这里是需要的数据
$rootScope.tags = response.data;
}, function(response) {
// 请求失败执行代码
console.log('request failed');
});
}
]);
// 在指令上绑定了run方法中获取的数据
BlogApp.directive('appPostTag', ['$http', function($http) {
return {
templateUrl: '/view/template/postTag.html',
restrict: 'ECAM',
replace: true,
scope: {
// postTagDatas: '='
},
controller: ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.postTagDatas = $rootScope.tags;
}],
link: function ($scope) {
}
};
}]);
run方法肯定是先于指令执行的,但是由于http请求是异步的,指令执行时数据并没有回调回来,导致tags是undefined,请问有办法让指令在run的请求之后再加载么,或者有其他什么办法可以满足我的这种需求?
还有一种办法是在controller中进行数据的请求,然后在html标签上通过属性进行数据的传递,但是这样我试过也会出现指令先于controller加载的情况。。。
可以内部给个初始化的值 舒大哥