source

지시문의 요소에 html을 추가하고 상호 작용할 로컬 함수를 만듭니다.

ittop 2023. 10. 24. 21:33
반응형

지시문의 요소에 html을 추가하고 상호 작용할 로컬 함수를 만듭니다.

인 마이 앵글JS application, 나는 곳곳에 다른 복잡한 입력들을 가지고 있습니다.예를 들어, 일부 입력에는 Google Places에서 자동 완성을 사용하거나 Twitter Bootstrap에서 자동 완성을 사용하라는 지시가 있습니다.

iOS 기능과 같은 텍스트를 추가할 때 지우기 버튼을 표시하는 지시문을 만드는 방법을 찾고 있습니다.

이거는 제가 만들었지만.scope.erase시작하지 않습니다.ng-show.

문자 입력 후 HTML을 추가하여 컨트롤러 내에서 '재생'할 수 있습니까?

내 테스트:

app.directive('eraseBtn', function($parse, $compile){

return {
    require: 'ngModel',
    restrict: "A",
    transclude: true,
    link : function(scope, element, attrs, model){

        element.parent().append('<button ng-click="erase()" ng-show="model.length > 0" class="erase-btn">x</button>');

        scope.erase = function(){
            console.log('Erase test');
        }
    }
}
});

제 입력의 HTML이 모두 다르기 때문에 템플릿을 사용하고 싶지 않습니다.

모델의 값에 따라 지시어의 링크 함수 내부에 사용자 정의 입력을 생성할 수 있습니다.해당 요소를 모델에 바인딩하거나 지침을 사용하여 구성하려면 다음을 사용해야 합니다.$compile(그리고 컴파일된 템플릿을 모델과 함께 호출하는 것을 잊지 마십시오):

HTML

<!DOCTYPE html>
<html ng-app="demo">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="demoController">
    <div demo-directive ng-repeat="input in inputs"></div>
  </body>

</html>

자바스크립트

angular.module('demo', []).
  controller('demoController', function($scope) {
    $scope.inputs = [{
      inputType: 'checkbox',
      checked: true,
      label: 'input 1'
    }, {
      inputType: 'text',
      value: 'some text 1',
      label: 'input 2'
    }];

    $scope.doSomething = function() {
      alert('button clicked');
    };
  }).
  directive('demoDirective', function($compile) {
    return {
      template: '<div><label>{{input.label}}: </label></div>',
      replace: true,
      link: function(scope, element) {
        var el = angular.element('<span/>');
        switch(scope.input.inputType) {
          case 'checkbox':
            el.append('<input type="checkbox" ng-model="input.checked"/><button ng-if="input.checked" ng-click="input.checked=false; doSomething()">X</button>');
            break;
          case 'text':
            el.append('<input type="text" ng-model="input.value"/><button ng-if="input.value" ng-click="input.value=\'\'; doSomething()">X</button>');
            break;
        }
        $compile(el)(scope);
        element.append(el);
      }
    }
  });

플렁커: http://plnkr.co/edit/pzFjgtf9Q4kTI7XGAUCF?p=preview

언급URL : https://stackoverflow.com/questions/21452706/append-html-to-an-element-in-directive-and-make-a-local-function-to-interact-wit

반응형