Angular.js - 从控制器到指令获取异步数据

时间:2015-01-21 12:08:37

标签: javascript angularjs asynchronous

我想创建一个控制器,从db获取数据并赋予指令。因此,当用户单击例如“新闻稿”文本时,异步数据将出现在另一个指令模板中。 如何从控制器向指令提供异步数据? 我通过php文件从数据库中获取数据。 这是代码:

    function newsletterController($scope, $http, loadFactory, newsletterFactory, $location) {

    $scope.id;
    $scope.title;

    $scope.getNews = function () {
        loadFactory.loadText();
        $location.path('/newsletter');
        $http.get('server/newsletter_title.php')
                .success(function (response, status) {
                    loadFactory.removeText();
                    for (var i in response.title) {
                            $scope.id = response.id[i];
                            $scope.title = response.title[i];
                            console.log('got it!!');                                                   
                    };
                });
    };
}

然后我想将这个异步数据添加到指令中。 这个指令是这样的:

angular.module('app')
    .controller('newsletterController', newsletterController)
    .directive('newsItem', function () {
        return{
            restrict: 'EA',
            link: function (scope, element, attr) {
                element.on('click', function () {
                    scope.getNews();
                        scope.$watch("id", function (newVal, oldVal) {
                            element.html(scope.id);
                            console.log("newsitem");
                    });

                });
            },
            template: "Newsletter"
        };
    })

然后添加另一个指令模板。 (也许我错了,可能是不必要的一步)

    .directive('dynamic', function () {
        return{
            restrict: 'EA',
            replace: true,
            link: function postLink(scope, element, attrs) {
                scope.$watch("id", function (newVal, oldVal) {
                    element.html(scope.id);
                    console.log("dynamic2");
                });
            },
            template: '<a class="btn btn-default btn-block" ng-repeat="Here is the id" >Here is the title</a>'
        };
    });

然而什么也没发生。

0 个答案:

没有答案
相关问题