$范围未在 DOM 中识别

问题描述 投票:0回答:1

我正在使用 OData Web API 将服务响应拉入 AngularJS。使用

$scope
在 DOM 中无法识别连接到我的控制器的
<div>
检查:

app.js

var productsApp = angular.module('productsApp', []);
var url = '/odata/Products';
productsApp.factory('productRepository', function ($http) {
    return {
        GetProducts: function (callback) {
            $http.get(url).success(callback);
        }
    }
});

productsApp.controller('prodCtrl', function ($scope, productRepository) {
    GetProducts();
    function GetProducts() {
        productRepository.GetProducts(function (results) {
            $scope.ProductData = results;
        })
    }

});

索引.cshtml

<!DOCTYPE html>
<html ng-app="productsApp">
<head lang="en">
    <meta charset="utf-8">
    <title>CRUD App using AngularJS</title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>
    <script src="~/Scripts/app.js"></script>


</head>
<body >
    <div ng-app="productsApp" ng-controller="prodCtrl">
        <ul ng-repeat="product in ProductData">
            <li>{{product.ID}}</li>
            <li>{{product.Name}}</li>
            <li>{{product.Price}}</li>
            <li>{{product.Category}}</li>

        </ul>
    </div>
</body>
</html>

产品.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProductService.Models
{
    public class Product
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Category { get; set; }
    }
}

产品控制器.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using ProductService.Models;

namespace ProductService.Controllers
{
/*
To add a route for this controller, merge these statements into the Register method of the WebApiConfig class. Note that OData URLs are case sensitive.

using System.Web.Http.OData.Builder;
using ProductService.Models;
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
*/
public class ProductsController : ODataController
{
    private ProductServiceContext db = new ProductServiceContext();

    // GET odata/Products
    [Queryable]
    public IQueryable<Product> GetProducts()
    {
        return db.Products;
    }

    // GET odata/Products(5)
    [Queryable]
    public SingleResult<Product> GetProduct([FromODataUri] int key)
    {
        return SingleResult.Create(db.Products.Where(product => product.ID == key));
    }

    // PUT odata/Products(5)
    public async Task<IHttpActionResult> Put([FromODataUri] int key, Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (key != product.ID)
        {
            return BadRequest();
        }

        db.Entry(product).State = EntityState.Modified;

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return Updated(product);
    }

    // POST odata/Products
    public async Task<IHttpActionResult> Post(Product product)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Products.Add(product);
        await db.SaveChangesAsync();

        return Created(product);
    }

    // PATCH odata/Products(5)
    [AcceptVerbs("PATCH", "MERGE")]
    public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Product> patch)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        Product product = await db.Products.FindAsync(key);
        if (product == null)
        {
            return NotFound();
        }

        patch.Patch(product);

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ProductExists(key))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return Updated(product);
    }

    // DELETE odata/Products(5)
    public async Task<IHttpActionResult> Delete([FromODataUri] int key)
    {
        Product product = await db.Products.FindAsync(key);
        if (product == null)
        {
            return NotFound();
        }

        db.Products.Remove(product);
        await db.SaveChangesAsync();

        return StatusCode(HttpStatusCode.NoContent);
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool ProductExists(int key)
    {
        return db.Products.Count(e => e.ID == key) > 0;
    }
}
}

当我使用 Google Chrome 并使用 F12 停止调试器时,我的

$scope.productsApp
数据可见,但在“元素”面板中,ng-repeat 中的
<li>
元素仅显示:

。
。
。
。
。

如果有人可以帮忙,我将不胜感激...... 谢谢

javascript angularjs angularjs-ng-repeat odata webapi
1个回答
0
投票

如果我添加:

{{ 产品数据 | json }}
它显示的数据如下:

  { "odata.metadata": "localhost:51811/odata/$metadata#Products",
     “价值”: [
              {“ID”:1,
                “名称”:“帽子”,
                “价格”:“15.00”,
                “类别”:“服装”
              }
              ]
  }

现在如何在

<li>{{product.ID}}</li>
中显示?

使用

$templateCache
for
循环作为替代方案:

var app = angular.module('foo', []);

function foo($templateCache)
  {
  var tmpl, lister,
  ProductData = 
    { "odata.metadata": "localhost:51811/odata/$metadata#Products", 
    "value": [
               {
               "ID": 1, 
               "Name": "Hat", 
               "Price": "15.00", 
               "Category": "Apparel" 
               }
             ]
    };

  lister = function()
  	{
    var index, replacement = "";
    for (index in this)
      {
      /* Avoid adding the callback function itself to the array */
      if (/\n/.test(this[index]) === false)
        {
        replacement = replacement.concat("<li>",this[index],"</li>");
        }
      }
    return replacement;
    };
    
  ProductData.value[0].toJSON = lister;
  tmpl = JSON.stringify(ProductData.value[0]).replace(/"/g,"");
  
  console.log(tmpl);
    
  $templateCache.put('listContent', tmpl);
  }

app.run(foo);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app="foo">
  <ul ng-include="'listContent'"></ul>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.