2017-09-26 55 views
1

我被AngularJS和JSON卡住了。 我有一個名爲form.html的視圖,允許用戶選擇他們的省份。 我創建了省JSON文件並放入選擇標記,但是當我存儲MySQL時,我需要一個省編號 我在選項標記中嘗試了ng-value =「province.id」,但不起作用。當用戶選擇省時,我怎樣才能同時獲得pid(provinceId)?如何從AngularJS中的JSON中獲取屬性並選擇表格

province.JSON

[ 
    { 
    "pid" : 1, 
    "name" : "Ontario" 
    }, 
    { 
    "pid" : 2, 
    "name" : "Québec" 
    }, 
    { 
    "pid" : 3, 
    "name" : "Nova Scotia" 
    }, 
    { 
    "pid" : 4, 
    "name" : "New Brunswick" 
    }, 
    ... 

form.html

<select name="province" ng-model="user.province" ng-required="true"> 
<option value="">--- Please select ---</option> 
<option ng-repeat="province in provinces">{{province.name}}</option> 
</select> 

controllers.js

$scope.submitForm = function (user) {    
    dataObj = { 
     "name": user.name,   //it works and all fine 
     "province": user.province, //it works and all fine 
     "telephone": user.telephone, //it works and all fine 
     "postalcode": user.postalcode, //it works and all fine 
     "salary": user.salary,   //it works and all fine 
     "provinceId" : user.pid  // undefine .. 
    } 
+0

和PHP的一部分是...? – Twinfriends

+0

''? –

+0

PHP有關係嗎?我認爲我的PHP是好的 – Jason

回答

0

試試這個:

var app = angular.module('myApp', []); 
 
app.controller('myCtrl', function($scope) { 
 
    $scope.user = {}; 
 
    $scope.provinces = [{ 
 
         "pid" : 1, 
 
         "name" : "Ontario" 
 
         }, 
 
         { 
 
         "pid" : 2, 
 
         "name" : "Québec" 
 
         }, 
 
         { 
 
         "pid" : 3, 
 
         "name" : "Nova Scotia" 
 
         }, 
 
         { 
 
         "pid" : 4, 
 
         "name" : "New Brunswick" 
 
         } 
 
         ]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
<select name="contactCountry" ng-model="user.province" ng-options="item.pid as item.name for item in provinces" ><option value="">Select provinces</option> 
 
</select> 
 
<br> 
 
<p>Selected Province Id = {{user.province}}</p> 
 
</div>

希望它可以幫助!。

+0

之前試過謝謝!它的工作原理,但我也需要province.name,以顯示如何在同一時間得到省名? – Jason

+0

謝謝,它實際上爲我編輯一些代碼我從你得到了一個概念謝謝! – Jason

+0

請接受我的回答.. – Raghav

0

當用戶提交選擇標籤會像{「PID:1」,「名」:「安大略」}對象,所以我可以在我的控制器獲取

關鍵是我應該做的oject。

HTML文件

<select name="province" ng-model="user.province" ng-options="item.name for item in provinces" class="form-control input-lg" ng-required="true"> 
    <option value="">Select provinces</option> 
<select> 

controllers.js

myFactory.set(user);     
    dataObj = { 
     "name": user.name, 
     "province": user.province.name, 
     "telephone": user.telephone, 
     "postalcode": user.postalcode, 
     "salary": user.salary, 
     "pid" : user.province.pid 
    }