Amit Kumar
Amit Kumar

Reputation: 5962

unable to get $scope value in partial view in mvc and angularjs

I want to load partial in my main. this my _layout.cshtml page.

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script src="~/Content/Angular/angular.min.js"></script>
    <script src="~/Content/Angular/ui-bootstrap-tpls.min.js"></script>
    <script src="~/Content/Angular/Module.js"></script>


</head>
<body ng-app="myapp">
    @Ajax.ActionLink("IMR", "Demo", "IMR", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divBody" })
    <div class="container body-content" id="divBody">
        @RenderBody()
    </div>
    @RenderSection("scripts", required: false)
</body>

As I have ajax action link on my layout page, which call the Demo action of IMR controller.

 public ActionResult Demo()  
        {
            return PartialView();
        }

This is my Demo partila view.

<script src="~/Content/Angular/IMRController.js"></script>
<div ng-controller="mycntrl">
    {{myname}}
</div>

Module.Js

var myApp = angular.module('myapp', []);

IMRController.js

myApp.controller("mycntrl", function ($scope) {
    $scope.myname = "Amit";
});

But in demo.cshtml, I click on IMR , it render partial view, but it doesn't show the value of myname It is showing expression in browser

{{myname}} 

Upvotes: 1

Views: 1374

Answers (1)

rtn
rtn

Reputation: 2034

In you angular controller create a a global function on the window:

window.update = function(){
 var scope = angular.element($("#div-where-ng-app-is")).scope();
    scope.$apply()
}

and in your asp control call the global function update() on Success:

@Ajax.ActionLink("IMR", "Demo", "IMR", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divBody", OnSuccess = "window.update()" })

Upvotes: 1

Related Questions