sourcetip

다른 ng-include가 같은 페이지에 있습니다.각자에게 다른 변수를 송신하려면 어떻게 해야 합니까?

fileupload 2023. 3. 14. 21:49
반응형

다른 ng-include가 같은 페이지에 있습니다.각자에게 다른 변수를 송신하려면 어떻게 해야 합니까?

angular Angular angular in 부분이지만 같은 html 부분이지만 변수가 다른 JS앱을 포함시키고 싶습니다.html:

<div id="div1" ng-include src="partials/toBeIncluded.html onload="var='A'">
<div id="div2" ng-include src="partials/toBeIncluded.html onload="var='B'">

★★★★★★★★★★★★★★★★★.toBeIncluded.html가 마치

<div>{{var}}</div>

다.div음 ' ' 、 、 、 、 、 、 。

<div id="div1"><div>B</div></div>
<div id="div2"><div>B</div></div>

것이 같은 하는 이 듭니다.onloadng에서 .그럼 어떻게 하면 각각 다른 변수를 보낼 수 있을까요?

.onload는 새로운 파셜이 로드될 때마다 평가됩니다.에는 '바뀌다'의 예요.var 번, 양쪽 은 " " "가 됩니다.B

각 부분/템플릿에 서로 다른 데이터를 전달해야 합니다(기본 html 파일은 동일).Tiago가 언급한 바와 같이 이를 실현하기 위해 다양한 컨트롤러를 사용할 수 있습니다.예를 들어, 다음과 같습니다.

<body ng-controller='MainCtrl'>    
  <div ng-include src='"toBeIncluded.html"' ng-controller='ctrlA' onload="hi()"></div>
  <div ng-include src='"toBeIncluded.html"' ng-controller='ctrlB' onload="hi()"></div>
</body>

파셜이 되고 있습니다(</FONT CHANGE/FONT CHANGE:</FONTHANGE:</FONT CHANGE:></FONT CHANGE:>.각각의 파셜은, 독자적인 컨트롤러로부터 관리되고 있습니다(ctrlA ★★★★★★★★★★★★★★★★★」ctrlB의 양쪽 :MainCtrl.기능hi()MainCtrl두 번 실행됩니다.

다음과 같은 컨트롤러가 있는 경우

app.controller('MainCtrl', function($scope) {
  $scope.msg = "Hello from main controller";
  $scope.hi= function(){console.log('hi');};
});

app.controller('ctrlA', function($scope) {
  $scope.v = "Hello from controller A";
});

app.controller('ctrlB', function($scope) {
  $scope.v = "Hello from controller B";
});

★★★★★★★★★★★★★★★★★★★★★★★★★★★★toBeIncluded.html

<p>value of msg = {{msg}}</p>
<p>value of v = {{v}} </p>

결과 html은 다음 행과 같은 것입니다.

<p>value of msg = Hello from main controller</p>
<p>value of v = Hello from main controller A </p>

그리고.

<p>value of msg = Hello from main controller</p>
<p>value of v = Hello from controller B </p>

예: http://plnkr.co/edit/xeloFM?p=preview

Mark가 말한 것처럼 조금 더 심플하고 '온더플라이'를 실현하려면 다음을 사용합니다.

<div ng-repeat="name in ['John']" ng-include="'name-template.html'"></div>
<div ng-repeat="name in ['Jack']" ng-include="'name-template.html'"></div>

<script type="text/ng-template" id="name-template.html">
   <div>The name is {{ name }}</div>
<script>

예: http://jsfiddle.net/Cndc6/4/

@jm-의 답변에 대한 코멘트에서 부분적인 inside ng-repeat을 로드하고 싶다고 말씀하셨습니다.이를 수행하려면 $scope에 어레이를 만들고 해당 어레이에 고유한 값을 설정합니다.

$scope.partialStuff = [ 'p1', 'p2', 'p3' ];

부분적인 부분:

{{partialVar}}

HTML:

<div ng-repeat="partialVar in partialStuff">
   <div ng-include src="'partials/toBeIncluded.html'"></div>
</div>

만지작거리다.

내가 틀릴 수도 있지만 지침을 사용하는 것이 더 낫지 않을까요?

.directive('foobar', [function factory() {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/toBeIncluded.html',
        scope: {
            "var": "="
        }
    };
}]);

HTML도

<div ng-repeat="var in data">
    <foobar var="var"></foobar>
</div>

이제 foobar 요소를 템플릿으로 대체해야 합니다.각자 자기 영역을 가지고 있어요

구체적으로는 ng-init 표현과 onload 표현은 nginclude에 의해 작성된 자 스코프가 아닌 부모 스코프로 평가됩니다.따라서 값을 할당해야 합니다.var두 번 모두 ng-module 내의 콘텐츠가 컴파일 및 평가되기 전에 발생합니다.각 하위 범위가 생성되면 상위 범위(var='B')에서 상속됩니다.

부분적인 부분 안에 가변 foo가 있다고 가정해봐

그러면 이렇게 foo를 지나가게 됩니다.

<ng-include src="'partials/foo-part.html'" onLoad="foo='bar'"></ng-include>

브라우저 호환성을 높이기 위해 다음과 같이 전달할 수 있습니다.

<div ng-include src="'partials/foo-part.html'" onLoad="foo='bar'"></div>

, 이렇게 하실 수 있습니다.onInclude="foo='bar'"onLoad

plnkr.co/edit/GHRNyAMBKLvgtf3NFSRu?p=info

모든 ng 포함에 대해 동일한 "onLoad"가 호출되는 것은 아닙니다.대부분의 경우 var는 A로, 다음으로 B로 설정됩니다.중요한 것은, 양쪽이 같은 범위에 있기 때문에, 양쪽에서 공유되고 있다는 것입니다."var"는 angularJS의 모델로서 스코프에 의존합니다.

파셜이 개별 값을 가지려면 각 파셜에 고유한 범위가 있어야 합니다.가장 쉬운 방법은 컨트롤러 또는 디렉티브를 설정하고 ng-include가 있는 돔 요소에 할당하여 해당 범위 내에서 값을 설정하는 것입니다.

나도 똑같은 문제를 겪었고 내가 원하는 것을 이룰 수 있는 방법을 찾았다. 물론 그렇게 예쁘지는 않지만 그래도 말이다.

ng-repeat을 사용하여 다음과 같은 다른 값을 가진 동일한 템플릿을 두 번 포함하도록 새로운 스코프를 작성했습니다(dummy 예:

<script type="text/ng-template" id="mod-edito.html">
<div class="mod-edito__media">
    <img ng-src="{{ edito.cover.src }}" />
</div>
</script>

<div>
    <ng-include ng-repeat="edito in [edito_object]" src="'mod-edito.html'"></ng-include>
    ...
    <ng-include ng-repeat="edito in [edito_other]" src="'mod-edito.html'"></ng-include>
</div>

괜찮으시겠어요?나도 그렇게 생각해.

다른 방법을 찾고 있었는데, js 오브젝트가 포함된 파셜에 몇 가지 파라미터를 보내 주길 원했습니다.이것은 @denis-pshenov가 만든 것을 진화시킨 것입니다.컨트롤러를 사용하여 데이터를 채우거나 ng-init을 사용할 수 있습니다.

기본적으로 이런 거 있잖아요

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

myApp.controller('Controller', function($scope) {
    $scope.ourData = [ { name : 'John', address : 'Paradise' } ];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="Controller">
    <div ng-repeat="data in ourData" ng-include="'partial.html'"></div>
    
    <div ng-init="ourData2 = [ { name : 'Jack', address : 'Paradise' } ]" />
    <div ng-repeat="data in ourData2" ng-include="'partial.html'"></div>
    
</div>

<script type="text/ng-template" id="partial.html">
   <div>The name is {{ data.name }} and the address is {{ data.address }} </div>
</script>

범용 재사용 디렉티브를 작성하는 방법이 있습니다.

여기 제 동료가 (Knockout.js에서 영감을 얻어) 생각해 낸 것이 있습니다.

지시:

(function () {
    'use strict';

    angular
        .module('directives')
        .directive('ngWith', ngWith);

    function ngWith() {
        return {
            restrict: 'A',
            replace: true,
            scope: {
                model: '=',
                template: '@'
            },
            template: '<div data-ng-include="template"></div>',
        };
    }
})();

사용방법:

<div data-ng-with="" data-model="parentObj.childObj.whatEver" data-template='my-template.html'></div>

ng-repeat에 partial을 포함하면 상위 스코프의 $index에 액세스할 수 있습니다.부분에는 {{$index}}을(를) 포함하면 됩니다.

온로드 사용은 글로벌 범위를 초과하기 때문에 클린 솔루션이 아닙니다.좀 더 복잡한 게 있으면 실패하기 시작할 거예요.

ng-include 대신 새로운 디렉티브를 사용하는 이 보다 깨끗한 솔루션입니다.

이상적인 사용법은 다음과 같습니다.

<div ng-include-template="partials/toBeIncluded.html" ng-include-variables="{ var: 'A' }"></div>
<div ng-include-template="partials/toBeIncluded.html" ng-include-variables="{ var: 'B' }"></div>

지시사항은 다음과 같습니다.

.directive(
  'ngIncludeTemplate'
  () ->
    {
      templateUrl: (elem, attrs) -> attrs.ngIncludeTemplate
      restrict: 'A'
      scope: {
        'ngIncludeVariables': '&'
      }
      link: (scope, elem, attrs) ->
        vars = scope.ngIncludeVariables()
        for key, value of vars
          scope[key] = value
    }
)

지시문이 글로벌스코프를 사용하지 않는 것을 알 수 있습니다.대신 ng-include-variables에서 개체를 읽고 해당 구성원을 자체 로컬 범위에 추가합니다.

ng-module은 글로벌스코프에 액세스 할 수 있기 때문에 재사용이 어렵습니다.조금 이상하네요.

이것이 당신이 좋아하는 것이기를 바랍니다. 깔끔하고 일반적이기 때문입니다.

다음과 같은 단일 값을 사용하여 기능을 참조할 수 있습니다.$scope.a = 'test'또, 다음과 같은 오브젝트에는$scope.a = {a.test};다른 스코프를 사용하여 가시성 영역을 정의합니다.

ng-if 문서에서.

ngIf를 사용하여 요소를 제거하면 해당 범위가 파괴되고 요소가 복원될 때 새 범위가 생성됩니다.

Simpe 솔루션은 다음을 포함합니다.ng-if정적 구성 요소를 정의하여ng-init지시.

<div ng-if="<any-true-expression>" ng-init="val='First'" ng-include="'html/common.html'"</div>

<div ng-if="<any-true-expression>" ng-init="val='Second'" ng-include="'html/common.html'"</div>

이 경우 다음과 같은 다른 값으로 표시됩니다.

{{val}} shows >>
First
Second

val은 가치에 대한 단순한 참조이므로 이 내용은 정적입니다.

일반적인 범위 값에 따라 동적으로 페이지를 변경할 수 있도록 하려면 지시문을 사용할 때 작성된 범위를 삭제하고 다시 생성해야 합니다.ng-if. 이렇게.

<div id="wrapper" ng-if="orders_client">
       <div id="client-orders" ng-init="orders = orders_client" ng-include="'html/pages/parts/orders-view.html'"></div>
</div>

그리고.

$scope.orders_client = null;
   /*recreate content table*/
     $timeout(function () {
        $rootScope.general.showPreloader = false;
        $scope.orders_client = $scope.baseData.clients[newClient];
     }, 500);

이 경우 이전 데이터가 포함된 스코프가 파기되고 새 데이터가 포함된 새로운 스코프가 생성됩니다.새로운 스코프 500ms를 재작성할 시간이 필요합니다.더 좋은 어획물이 있으면 써주세요.

사용할 수 있습니다.ng-if=true를 로딩할 때마다 새로운 스코프를 강제하다ng-include.

당신의 코드는 다음과 같습니다.

<div id="div1" ng-include src="partials/toBeIncluded.html onload="var='A'" ng-if="true">
<div id="div2" ng-include src="partials/toBeIncluded.html onload="var='B'" ng-if="true">

플런커에서 예를 찾을 수 있습니다.

여기서 같은 아이디어를 참조하는 또 다른 답변

각 ng-include를 자체 아래에 넣습니다.<div>다음과 같습니다.

<div>
  <div id="div1" ng-include src="partials/toBeIncluded.html onload="var='A'"/>
</div>
<div>
  <div id="div2" ng-include src="partials/toBeIncluded.html onload="var='B'"/>
</div>

그 후, 각 HTML은 독자적인 것이 됩니다.var그 자체 범위 내에서.

언급URL : https://stackoverflow.com/questions/13811948/different-ng-includes-on-the-same-page-how-to-send-different-variables-to-each

반응형