简体   繁体   English

如何使用Angular.js将值传递给指令隔离范围

[英]How to pass value to directive isolated scope using Angular.js

I need to pass value from array to directive scope using Angular.js. 我需要使用Angular.js将值从数组传递到指令范围。 My code is shown below. 我的代码如下所示。

test.html: 的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: 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. 数组中有mp3列表,我的要求是用户仅在文本字段中输入索引值,然后单击“播放”按钮。 That index vale will match with that mp3 array list and that particular track will play. 该索引值将与该mp3数组列表匹配,并且将播放该特定曲目。 I need it using the directive. 我需要使用指令。

You have to create an html attribute to pass your array into your directive, here is an example: 您必须创建一个html属性才能将数组传递到指令中,这是一个示例:

form-input.directive.js: 外形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: 外形input.html:

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

index.html: 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. mp3Array是一个数组,其中mp3曲目在html页面访问的控制器中定义。

Here is the angularjs directive documentation, you can find an other example of isolated scope use. 这是angularjs指令文档,您可以找到隔离范围使用的另一个示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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