programing

기본값에서 각도 js init ng-model

oldcodes 2023. 3. 25. 11:53
반응형

기본값에서 각도 js init ng-model

데이터베이스에서 값이 로드된 양식이 있다고 가정합니다.ng-model은 어떻게 초기화합니까?

예:

<input name="card[description]" ng-model="card.description" value="Visa-4242">

컨트롤러에서 $scope.card는 처음에 정의되어 있지 않습니다.이런 거 말고 다른 방법이 있나요?

$scope.card = {
  description: $('myinput').val()
}

@blesh가 제안하는 것을 실행하도록 앱을 변경할 수 없는 경우($http 또는 $resource로 JSON 데이터를 풀다운하고 $scope를 채우는 경우) 대신 ng-init를 사용할 수 있습니다.

<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">

'각'도 참조JS - ng-model이 사용되는 경우 입력 텍스트 상자의 값 속성이 무시됩니까?

이것은 새로운 Angular 어플리케이션에서 흔히 볼 수 있는 실수입니다.피할 수 있는 경우 서버의 HTML에 값을 쓰고 싶지 않습니다.사실, 서버가 HTML을 완전히 렌더링하는 것을 피할 수 있다면, 훨씬 더 좋습니다.

이상적으로는 Angular HTML 템플릿을 전송하고 JSON의 $http를 통해 값을 끌어내려서 스코프에 넣는 것이 좋습니다.

가능한 경우 다음 작업을 수행합니다.

app.controller('MyController', function($scope, $http) {
    $http.get('/getCardInfo.php', function(data) {
       $scope.card = data;
    });
});

<input type="text" ng-model="card.description" />

반드시 서버에서 HTML로 값을 렌더링해야 하는 경우 글로벌 변수에 값을 넣고 $window를 사용하여 액세스할 수 있습니다.

페이지 머리글에는 다음과 같이 적습니다.

<head>
   <script>
       window.card = { description: 'foo' };
   </script>
</head>

그리고 컨트롤러에서는 다음과 같이 표시됩니다.

app.controller('MyController', function($scope, $window) {
   $scope.card = $window.card;
});

이것은 분명히 부족하지만 AngularJS에는 쉽게 추가할 수 있는 수정입니다.입력 필드에서 모델 값을 설정하는 간단한 지시문을 작성하기만 하면 됩니다.

<input name="card[description]" value="Visa-4242" ng-model="card.description" ng-initial>

내 버전은 다음과 같습니다.

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

app.directive('ngInitial', function() {
  return {
    restrict: 'A',
    controller: [
      '$scope', '$element', '$attrs', '$parse', function($scope, $element, $attrs, $parse) {
        var getter, setter, val;
        val = $attrs.ngInitial || $attrs.value;
        getter = $parse($attrs.ngModel);
        setter = getter.assign;
        setter($scope, val);
      }
    ]
  };
});

IMHO의 가장 좋은 솔루션은 @Kevin Stone 디렉티브입니다만, 모든 조건(text area 등)에서 동작하도록 업그레이드 할 필요가 있었습니다.이 솔루션은 확실히 동작하고 있습니다.

    angular.module('app').directive('ngInitial', function($parse) {
        return {
            restrict: "A",
            compile: function($element, $attrs) {
                var initialValue = $attrs.value || $element.val();
                return {
                    pre: function($scope, $element, $attrs) {
                        $parse($attrs.ngModel).assign($scope, initialValue);
                    }
                }
            }
        }
    });

커스텀 디렉티브(text area, select, radio 및 체크박스를 지원)를 사용할 수 있습니다.이 블로그 포스트는 https://glaucocustodio.github.io/2014/10/20/init-ng-model-from-form-fields-attributes/ 에서 확인할 수 있습니다.

코드 내에서 .HTML 코드 내에서 사용할 수 .ng-init="card.description = 12345"

Angular에서는 권장하지 않으며 위에서 설명한 바와 같이 전용 컨트롤러를 사용해야 합니다.

하지만 효과가 있습니다:)

난 간단한 방법을 택했어 내 폼에 무거운 검증과 마스크가 있거든그래서 jquery를 사용하여 가치를 다시 얻고 검증에 대한 이벤트 "변경"을 실행했습니다.

$('#myidelement').val('123');
$('#myidelement').trigger( "change");

다른 사람들이 지적했듯이 뷰에 대한 데이터를 초기화하는 것은 좋지 않습니다.그러나 컨트롤러의 데이터를 초기화하는 것이 좋습니다.(http://docs.angularjs.org/guide/controller) 참조).

그래서 너는 글을 쓸 수 있다.

<input name="card[description]" ng-model="card.description">

그리고.

$scope.card = { description: 'Visa-4242' };

$http.get('/getCardInfo.php', function(data) {
   $scope.card = data;
});

이렇게 하면 뷰에 데이터가 포함되지 않으며 실제 값이 로드되는 동안 컨트롤러가 값을 초기화합니다.

위의 Kevin Stone의 접근방식이 마음에 든다면, 'input'과 같은 특정 태그에 대한 지침을 작성하는 것이 더 쉬운 접근방식을 고려해 보십시오.

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
            }
        }
    }; });

이 루트를 사용하면 모든 태그에 ng-initial을 추가할 필요가 없습니다.모델의 값을 태그의 값 속성으로 자동으로 설정합니다.값 속성을 설정하지 않으면 기본적으로 빈 문자열이 됩니다.

서버 중심의 접근방식은 다음과 같습니다.

<html ng-app="project">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script>
        // Create your module
        var dependencies = [];
        var app = angular.module('project', dependencies);

        // Create a 'defaults' service
        app.value("defaults", /* your server-side JSON here */);

        // Create a controller that uses the service
        app.controller('PageController', function(defaults, $scope) {
            // Populate your model with the service
            $scope.card = defaults;
        });
    </script>

    <body>
        <div ng-controller="PageController">
            <!-- Bind with the standard ng-model approach -->
            <input type="text" ng-model="card.description">
        </div>
    </body>
</html>

$provide.value가 기본값을 포함하는 서비스를 등록하는 것을 제외하고 이 질문에 대한 더 일반적인 답변과 동일한 기본 개념입니다.

서버에는 다음과 같은 것이 있습니다.

{
    description: "Visa-4242"
}

선택한 서버측 테크놀로지를 통해 페이지에 넣을 수 있습니다.다음은 Gist: https://gist.github.com/exclsr/c8c391d16319b2d31a43

이것은 위에서 언급한 아이디어의 보다 일반적인 버전입니다.모형에 값이 있는지 확인하고 없으면 모형에 값을 설정합니다.

JS:

function defaultValueDirective() {
    return {
        restrict: 'A',
        controller: [
            '$scope', '$attrs', '$parse',
            function ($scope, $attrs, $parse) {
                var getter = $parse($attrs.ngModel);
                var setter = getter.assign;
                var value = getter();
                if (value === undefined || value === null) {
                    var defaultValueGetter = $parse($attrs.defaultValue);
                    setter($scope, defaultValueGetter());
                }
            }
        ]
    }
}

HTML(사용 예):

<select class="form-control"
        ng-options="v for (i, v) in compressionMethods"
        ng-model="action.parameters.Method"
        default-value="'LZMA2'"></select>

나는 @Mark Rajcok이 제안한 것을 시도했다.String 값(Visa-4242)에 대해 동작합니다. 바이올린을 참고하세요.

바이올린부터:

은, 이이 the the를 사용해 실시할 수 .ng-repeat @읽고 같은 것을 해 보고 .하지만 @Mark Rajcok의 답변을 읽은 후, 저는 프로필이 배열된 폼에 대해 같은 답변을 시도하고 싶었습니다.컨트롤러에 $124.dev = [{},{}; 코드가 있을 때까지 잘 작동합니다.이 코드를 제거하면 오류가 발생합니다., 에서는, 는 할 수 .$scope.profiles = [{},{}];html을 사용하다@과 같은 @Mark Rajcok과 같은 의 작업을 할 수 ?<input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">자바스크립트

Ryan Montgomery "수정"에 선택 요소 지원 추가

<select class="input-control" ng-model="regCompModel.numberOfEmployeeId" ng-initial>
    <option value="1af38656-a752-4a98-a827-004a0767a52d"> More than 500</option>
    <option value="233a2783-db42-4fdb-b191-0f97d2d9fd43"> Between 250 and 500</option>
    <option value="2bab0669-550c-4555-ae9f-1fdafdb872e5"> Between 100 and 250</option>
    <option value="d471e43b-196c-46e0-9b32-21e24e5469b4"> Between 50 and 100</option>
    <option value="ccdad63f-69be-449f-8b2c-25f844dd19c1"> Between 20 and 50</option>
    <option value="e00637a2-e3e8-4883-9e11-94e58af6e4b7" selected> Less then 20</option>
</select>

app.directive('ngInitial', function () {
return {
    restrict: 'A',
    controller: ['$scope', '$element', '$attrs', '$parse', function ($scope, $element, $attrs, $parse) {
        val = $attrs.sbInitial || $attrs.value || $element.val() || $element.text()
        getter = $parse($attrs.ngModel)
        setter = getter.assign
        setter($scope, val)
    }]
}

});

에 "URL"과 같은 init 값은 "URL" 입니다.mypage/id에서는 JS를 사용할 수 location.pathname아이디 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」

언급URL : https://stackoverflow.com/questions/13769732/angular-js-init-ng-model-from-default-values

반응형