Hryhorii
Hryhorii

Reputation: 1243

AngularJS controller not working

I have AngularJS v1.2.19. I try use in my project

in body tag I wrote

<body ng-app="commentApp">

in page for calling controller I use

<div ng-controller="CommentLstCtrl">
    @{ Html.RenderPartial("Partial/CommentList", @Url.Action("Comments", "News")); }
    @{ Html.RenderPartial("Partial/CommentForm"); }
</div>

In js file I wrote

$(document).ready(function () {
    var url = $("#comments").attr("data-source");
    var id = $(".news-post").attr("data-id");
    var app = angular.module('commentApp', []);

    $.ajax({
        url: url,
        data: { newsId: id },
        type: "POST",
        dataType: "json",
        success: function (data) {


            app.controller("CommentLstCtrl", function ($scope) {
                $scope.comments = [
                    {
                        'text': 'Fast just got faster with Nexus S.'
                    },
                    {
                        'text': 'The Next, Next Generation tablet.'
                    },
                    {
                        'text': 'The Next, Next Generation tablet.'
                    }
                ];
            });
        }
    });
});

But code not working. When I debug this code, I saw that not come in body controller. And I can't understand why?

Upvotes: 2

Views: 169

Answers (1)

vittore
vittore

Reputation: 17579

1) Move

app.controller("CommentLstCtrl", function ($scope) {
            $scope.comments = [
                { 'text': 'Fast just got faster with Nexus S.' },
                { 'text': 'The Next, Next Generation tablet.'  },
                {  'text': 'The Next, Next Generation tablet.' }
            ];
});

outside of ajax call.

2) Use angular.bootstrap(document.querySelector('body'), ['commentApp']) to start application once ajax call succeeds

3) Show rendered content of your partial views. It is happening on the server side, not in the browser.

Upvotes: 1

Related Questions