2016-10-13 3 views
1

내 응용 프로그램 페이지에 매우 큰 폼이 있으며 JSON 변수가 있습니다. 여기서 모든 폼 데이터를 저장하고 controllerAs 식을 사용하고 있습니다.Angular에서 HTML 블록의 범위를 정의하는 방법은 무엇입니까?

<form> 
    <input type="text" data-ng-model="ctrl.myJSON.name"/> 
    <input type="text" data-ng-model="ctrl.myJSON.old"/> 
    <input type="text" data-ng-model="ctrl.myJSON.address"/> 
    <input type="text" data-ng-model="ctrl.myJSON.email"/> 
    <input type="text" data-ng-model="ctrl.myJSON.phone"/> 
    <!-- and many more... --> 
</form> 

방법에 내가 필요없이 모든 분야에서이 변수 많은 시간을 반복, 양식 범위로 myJSON를 정의 할 수 있습니다?

답변

1

각도 확장을 사용하여 json 데이터를 $ scope에 복사 할 수 있습니다. 그리고, 당신이 직접 사용할 수 있습니다 : 그 후

.controller('YourController', function($scope) { 

    $scope.readData = function() { 
     // replace with your read data function 
     var myJSON = { name: 'test' }; 
     angular.extend($scope, myJSON); 
    } 

} 

을, 변수를 직접 작동합니다

<input type="text" data-ng-model="name"/> 
+0

나는 어쩌면이 방법 더러운 범위 및 HTML 블록 – Lai32290

+0

의 다른 부분에 오버 플로우 생각 승 음, JSON의 내용이 바뀌면 다소 침입 적입니다. angle.extend (this, myJSON) 또는 제한된 속성을 확장 할 수 있습니다. angular.extend ($ scope, {name : myJSON.name, old : myJSON.old}) –

1

형태로 별도의 전용 컨트롤러 FormController 내부와 myJson 키 - 값 쌍을 복사 그것의 $scope에.

This is possible 범위 상속/중첩 범위를 사용하여 이후 버전의 각도로 표시합니다.

HTML

<div ng-controller="MainController"> 
    <form ng-controller="FormController"> 
     <input type="text" data-ng-model="name"/> 
     <input type="text" data-ng-model="old"/> 
     <input type="text" data-ng-model="address"/> 
     <input type="text" data-ng-model="email"/> 
     <input type="text" data-ng-model="phone"/> 
     <!-- and many more... --> 
    </form> 
</div> 

자바 스크립트

var myApp = angular.module('myApp', []); 
myApp.controller('MainController', ['$scope', function($scope) { 
    // other logic goes here 
}]); 
myApp.controller('FormController', ['$scope', function($scope) { 
    // Initialize myJson by loading its data from a service 

    angular.extend($scope, myJson); 
}]); 

JSFiddle :https://jsfiddle.net/206redxb/5

관련 문제