我試圖創建一個數組拿着電話一個數組,我有這樣的代碼如何創建與AngularJS的NG-模式
<input type="text" ng-model="telephone[0]" />
<input type="text" ng-model="telephone[1]" />
但我不能訪問$ scope.telephone
我試圖創建一個數組拿着電話一個數組,我有這樣的代碼如何創建與AngularJS的NG-模式
<input type="text" ng-model="telephone[0]" />
<input type="text" ng-model="telephone[1]" />
但我不能訪問$ scope.telephone
的第一件事是第一次。您需要在控制器中將$scope.telephone
定義爲數組,然後才能在視圖中開始使用它。
$scope.telephone = [];
爲了解決NG-模型時,您將追加一個新的輸入不被識別的問題 - 對於工作,你必須使用$compile
角度的服務。
從Angular.js API reference on $compile:
編譯HTML字符串或DOM成模板,併產生一個模板函數,那麼它可以用來鏈接在一起範圍和模板。
// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');
// Compile the HTML and assign to scope
var compile = $compile(input)($scope);
將$添加到作用域 - > $ scope – Heroselohim
只是想知道,*「To解決ng-model在追加新輸入時無法識別的問題*「 - 此問題在哪裏? –
@TJ這是一個問題,一旦你會嘗試在沒有$編譯的情況下執行 –
它對我來說工作得很好:http://jsfiddle.net/qwertynl/htb9h/
我的javascript:
var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
$scope.telephone = []; // << remember to set this
}]);
有人可以解釋downvote嗎? – qwertynl
它完美的工作在jsfiddle,但是當我創建輸入元素與查詢的追加它不起作用,你知道爲什麼嗎? – DelGiudice
你是什麼意思@ user1870612?你可以創建一個演示嗎? – qwertynl
你可以做各種各樣的THI NGS。我會做的是這個。
在作用域上創建一個數組,作爲電話號碼的數據結構。
$scope.telephone = '';
$scope.numbers = [];
然後在你的HTML我有這個
<input type="text" ng-model="telephone">
<button ng-click="submitNumber()">Submit</button>
然後,當用戶點擊提交,運行submitNumber(),其推動新的電話號碼爲數字陣列。
$scope.submitNumber = function(){
$scope.numbers.push($scope.telephone);
}
您的ng點擊屬性需要一些修正,順便說一句。 – m0gg
這應該有效。
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.users = ['bob', 'sean', 'rocky', 'john']
$scope.test = ->
console.log $scope.users
HTML:
<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />
一種方式看看是你的數組轉換爲一個對象,並在範圍內使用它(一個數組的模擬)。這種方式有利於維護模板。
$scope.telephone = {};
for (var i = 0, l = $scope.phones.length; i < l; i++) {
$scope.telephone[i.toString()] = $scope.phone[i];
}
<input type="text" ng-model="telephone[0.toString()]" />
<input type="text" ng-model="telephone[1.toString()]" />
和保存,它改回來。
$scope.phones = [];
for (var i in $scope.telephone) {
$scope.phones[parseInt(i)] = $scope.telephone[i];
}
你能顯示你的javascript代碼嗎? – qwertynl
創建一個數組? 'ng-model'不會創建任何東西,它會綁定某些東西。使用'$ scope.telephone = [...]'或'ng-init'創建一個新模型。 – plalx
確切的問題是什麼? – SET