"Encountering a challenge when trying to populate a partial view using AngularJs and MVC

I am a beginner in AngularJS and I'm using a partial view for Create and Edit operations, but I'm encountering issues while trying to retrieve the data.

The data is successfully being retrieved from my MVC controller but it's not populating the view.

Below is the JavaScript code I am utilizing:

(function (angular) {
    'use strict';
    angular.module('Sub_Ledger_Category_Create_app', [])
.controller('Sub_Ledger_Category_Create_ctrl', function ($scope, $http, $location) {

    $scope.SubLedgerCategoryModel = {};
    GetRequestType();

    function GetRequestType() {
        $http.get('/Common/Get_Action_Request')
        .success(function (result) {
            if (result == "Create") {
                $("#txt_Master_Subledger_Category").html("<h3  class='box-title'> Create Sub Ledger Category </h3>");
            }
            else {
                $("#txt_Master_Subledger_Category").html("<h3  class='box-title'> Edit Sub Ledger Category</h3>");
                $scope.GetEditData();
            }
            $("#Master_Subledger_Category").val(result)

            NProgress.done();
        })
        .error(function (data, status, headers, config) {
            NProgress.done();
            $("div.failure").text("Unable to retrieve Request Type");
            $("div.failure").fadeIn(300).delay(1500).fadeOut(400);
        });
    };

     $scope.GetEditData = function () {
        $http.get('/Master_Subledger_Category/GetEditData')
        .success(function (data, status, headers, config) {
             $scope.SubLedgerCategoryModel = data;

            console.log(data);
        })
        .error(function (data, status, headers, config) {
            NProgress.done();
             $("div.failure").text("Retrive Failure");
             $("div.failure").fadeIn(300).delay(1500).fadeOut(400);
        });
    };


    $scope.InsertSubledgerCategory = function () {
        NProgress.start();
        var Request_Type = $("#Master_Subledger_Category").val();

        var Url_Master_Subledger;
        if (Request_Type == "Create") {
            Url_Master_Subledger = "/Master_Subledger_Category/Create_Master_Subledger_Category_Ajax";
        }
        else {
            Url_Master_Subledger = "/Master_Subledger_Category/Test";
        }

        $http({
            method: 'POST',
            url: Url_Master_Subledger,
            data: $scope.SubLedgerCategoryModel
        }).success(function (data, status, headers, config) {
            if (data.success === true) {
                NProgress.done();
                $("div.success").text("Successfully Created");
                $("div.success").fadeIn(300).delay(1500).fadeOut(800);
                $scope.SubLedgerCategoryModel = {};
                console.log(data);
            }
            else {
                NProgress.done();
                $("div.failure").text("Saving Failure");
                $("div.failure").fadeIn(300).delay(1500).fadeOut(400);
            }
        }).error(function (data, status, headers, config) {
            NProgress.done();
            $("div.failure").text("Saving Failure");
            $("div.failure").fadeIn(300).delay(1500).fadeOut(400);
            console.log($scope.message);
        });

    };


})
    .config(function ($locationProvider, $sceProvider) {
        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false
        });
        $sceProvider.enabled(false);

    });
})(angular);

Below is the HTML:

<div class="form-horizontal" ng-app="Sub_Ledger_Category_Create_app">
            <div class="box-body" ng-controller="Sub_Ledger_Category_Create_ctrl">
                <div class="form-group">
                    <label for="txt_Master_Subledger_Category_Name" class="col-sm-2 control-label">Sub Ledger Category</label>
                    <div class="col-sm-10">
                        <input class="form-control" ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_Name" id="txt_Master_Subledger_Category_Name" name="txt_Master_Subledger_Category_Name" autofocus placeholder="Sub Ledger Category">
                        <input ng-model="SubLedgerCategoryModel.Sub_Ledger_Cat_ID" name="txt_Master_Subledger_Category_ID" id="txt_Master_Subledger_Category_ID" hidden />
                    </div>
                </div>



                <!-- /.box-body -->
                <div class="box-footer">
                    <button type="submit" value="Save" ng-click="InsertSubledgerCategory()" class="btn btn-info pull-right">Save</button>

                    <div class="text-red alert-box failure pull-right margin-r-5"></div>

                    <div class="text-green alert-box success pull-right margin-r-5"></div>


                </div>
                <!-- /.box-footer -->
            </div>

        </div>

Despite being able to see the data in Console log, I'm struggling to populate the view. Any assistance would be greatly appreciated.

Answer №1

AngularJs blocks loading HTML in this manner as a security measure. If you encounter an error in the browser console saying attempting to use an unsafe value in a safe context, it is because of Angular's Strict Contextual Escaping (SCE) mode, which is on by default. For more details, check out this link.

To fix this issue, you have two options:

  1. $sce

    $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);

  2. ngSanitize: include the angular-sanitize.min.js file and add the dependency to your module.

I hope this information proves useful.

Answer №2

All I had to do was update one line of code:

scope.SubLedgerCategoryModel = data;

to

scope.SubLedgerCategoryModel = data[0]:

This simple change resolved the issue I was facing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to use createElement in JavaScript to insert <p> and <span> elements within a <div>?

I am currently experimenting with generating sentences accompanied by draggable text boxes. To achieve this, I intend to construct the following HTML structure using JavaScript exclusively: <div> <p>Data1<span class = "smallBox droppabl ...

(Typescript) The 'window' property is not present in the 'Global' type

Currently, I am utilizing Mocha/Chai for unit testing and have decided to mock the window object like so: global.window = { innerHeight: 1000, innerWidth: 1000 }; As expected, TSLint is raising an issue stating: Property 'window' does not ex ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

Addressing Equity Concerns within JavaScript Programming

I can't figure out why the final line in this code snippet is returning false. Is it not identical to the line above? const Statuses = Object.freeze({ UNKNOWN : 0, OK : 1, ERROR : 2, STOPPED : 3 }); class myStatus extends Object{ co ...

Is there a way to simplify and optimize the code further?

Here is the code snippet from my index.blade.php: HTML @foreach($sesis as $sesi) <td>{{ $sesi->waktu }} <label class="switch switch-text switch-info switch-pill" id="label-switch{{ $sesi->id } ...

Modifying parent scope upon updating view template with ng-include

I am facing an issue with a controller that switches between views using two ng-include directives, one for the view and the other for the edit screen. <div class="content-area"> <div class='row'> <div class="cs-info"> ...

Angular 2 - Error: Regular expression missing forward slash syntax

Recently, I began working on an Angular 2 tutorial app using this repository. While I can successfully launch the app and display static content, I am facing challenges with rendering dynamic content from the component. I have a feeling that the error migh ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

When running npm install, the dist folder is not automatically generated

I found a helpful tutorial at this link for creating a Grafana plugin. However, when I tried copying the code from this link to my test server (without the dist/ folder) and ran npm install, it did not generate a new dist/ folder but created a node_module ...

A step-by-step guide on enabling Autoclick for every button on a webpage

I am currently using Jquery and Ajax to carry out an action, my goal is for a code to automatically click on every button once the page has finished loading. Although I attempted to use the following javascript code to achieve this at the end of my page, ...

Ways to interact with similar dynamic controls in Javascript

I have an aspx page with a Select box control: <select name="selViewPerPage" id="selViewPerPage" style="width:30px"> To ensure consistent styling across all browsers, I am replacing this html control with a dynamic select box using "selectBox.js". ...

What is the best way to resolve an npm build error on Windows 10?

I have exhausted all options but still cannot successfully install any npm modules. Any suggestions on how to resolve this issue? Microsoft Windows [Version 10.0.17134.590] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\Dell&bsol ...

Unknown individual, yet revealed by the investigator

I'm attempting to develop a dynamic list in react.js generateList = () =>{ return this.state.user.map((u)=>{ console.log(u); return <li onClick={this.handleClick} id={u} name={u}>{u}</li>; }); } The hand ...

Ext.js Ext.grid.Panel with advanced filtering capabilities

I encountered an issue with the following code snippet... Ext.define("Requestor.view.main.RequestGrid", { extend: 'Ext.grid.Panel', // Our base class. A grid panel. ... extensive code ... columns: [ ... additional code ... { ...

Tips for creating visually appealing text on a web browser with the help of open-source libraries

Have you ever noticed that no matter how we display text on webpages, whether it's in a <p> tag or an <h1> tag, the result is always the same? (a screenshot of a rendering done in Firefox) Do you struggle with pixelated areas on the curv ...

IE8 does not support Jquery ajax() for cross domain requests to remote servers

My current script includes an ajax request to a remote server that provides a plain text response. This setup functions properly in all browsers with the exception of IE8, which is not surprising. The script snippet looks like this: $.ajax({ url: &apos ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

How to obtain the value of TR in JavaScript?

Objective: Extract the value "2TR" from "MARSSTANDGATA132TR" using JavaScript. Need to determine the location of the digit 2 within the extracted string. Issue: Uncertain about the correct syntax to achieve this task. Additional Details: *The cha ...

Tips for Selecting the DIV Element using jQuery

I am faced with the challenge of integrating this particular set of div tags: <div id="target-share"> <a href="#" title="" id="to-chosen" class="default"><span class="to-admin">Admin</span></a> <ul id="select-shareto"> ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...