DOM中未标识$ scope

时间:2014-05-12 16:34:20

标签: angularjs api web angularjs-ng-repeat odata

我正在使用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;
        })
    }

});
  

Index.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>
  

Products.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; }
    }
}
  

ProductsController.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;
    }
}
}

当我使用谷歌浏览器并使用F12停止调试时,我的$scope.productsApp数据可见,但在元素面板中,ng-repeat中的<li>元素仅显示:

.
.
.
.
.

如果有人可以提供帮助,我会很感激... 感谢

1 个答案:

答案 0 :(得分:0)

  

如果我添加:  

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

 
  { "odata.metadata": "localhost:51811/odata/$metadata#Products", 
     "value": [
              { "ID": 1, 
                "Name": "Hat", 
                "Price": "15.00", 
                "Category": "Apparel" 
              }
              ]
  }
  

现在如何在<li>{{product.ID}}</li>中显示?

使用$templateCachefor循环替代:

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;