简体   繁体   中英

How to pass value to directive isolated scope using Angular.js

I need to pass value from array to directive scope using Angular.js. My code is shown below.

test.html:

<html><head>
<!--music_append_class-->
<script src="js/angular.min.js"></script>
<script src="test.js"></script>
</head>
<body ng-app="formComponents">
    <form-input label="Name" form-id="nameInput">
      <input type="text" name="ind" id="ind" ng-model="index">
      <button type="button"  id="btn" ng-click="playAudio(index);">Play</button>
    </form-input>
</body>
</html>

test.js:

var app=angular.module('formComponents', [])
app.directive('formInput', function($document) {
    var audio = $document[0].createElement('audio');
    var trackList=[{'track':'audio_file.mp3'},
                   {'track':'audio_file1.mp3'},
                   {'track':'audio_file2.mp3'},
                   {'track':'audio_file3.mp3'}];
    return {
        restrict: 'E',
        scope: { src: '='},
    }
})

There are mp3 list is present in an array and my requirement is user only input the index value in text field and click on play button. That index vale will match with that mp3 array list and that particular track will play. I need it using the directive.

You have to create an html attribute to pass your array into your directive, here is an example:

form-input.directive.js:

app.directive('formInput', function() {
    return {
        restrict: 'E',
        scope: {
            mp3Track: '='
        },
        controller: formInputCtrl,
        transclude: true,
        templateUrl: './form-input.html'
    };
});

formInputCtrl.$inject = ['$scope'];

function formInputCtrl($scope) {
    $scope.playAudio(index) = playAudio;

    function playAudio(index) {
        var track = $scope.mp3Track[index];

        // DO OTHER STUFF WITH THE TRACK
    }
}

form-input.html:

<div class="audio-input" ng-transclude>
    // input and button will be inserted here by angularjs
</div>

index.html:

<form-input label="Name" form-id="nameInput" mp3-track="mp3Array">
  <input type="text" name="ind" id="ind" ng-model="index">
  <button type="button"  id="btn" ng-click="playAudio(index);">Play</button>
</form-input>

mp3Array is an array with your mp3 tracks wich is defined in the controller reached by your html page.

Here is the angularjs directive documentation, you can find an other example of isolated scope use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM