我正在做一个简单的教程,无法通过一个非常简单的事情。
我想在页面加载时创建一个元素。我已经完全按照代码进行了。我正在使用谷歌浏览器。以下不会创建音频元素的错误是什么?:
索引.html
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div ng-controller="PlayerController">
<button ng-click="play()" class="button" ng-show="!playing">Play</button>
<button ng-click="stop()" class="button alert" ng-show="playing">Stop</button>
Playing audio: <b>{{ playing }}</b>
</div>
</body>
</html>
main.js(在引用的位置 js/main.js 中)
var app = angular.module('myApp', []);
app.controller('PlayerController', ['$scope', function($scope) {
$scope.playing = false;
$scope.div = document.createElement("div");
$scope.audio = document.createElement('audio');
$scope.audio.src = 'media/sample_mpeg4.mp4';
}]);
这是页面检查时源代码的样子:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div ng-controller="PlayerController">
<button ng-click="play()" class="button" ng-show="!playing">Play</button>
<button ng-click="stop()" class="button alert" ng-show="playing">Stop</button>
Playing audio: <b>{{ playing }}</b>
</div>
</body>
</html>
如您所见,未创建音频元素。我尝试了更简单的示例,我尝试添加一个 div。
谢谢
最佳答案
一些事情:
相反,您可以通过以下方式进行探索:
<div player-directive="media/sample_mpeg4.mp4"></div>
并创建一个指令
app.directive('playerDirective', function() {
return {
restrict: 'A',
template: '<button ng-click="play()" class="button" ng-show="!playing">Play</button><button ng-click="stop()" class="button alert" ng-show="playing">Stop</button>Playing audio: <b>{{ playing }}</b>',
link: function (scope, element, attrs) {
var audioSrc = attrs.playerDirective,
div = angular.element('<div/>'),
audio = angular.element('<audio/>')
.attr('src', audioSrc);
element.append(div.append(audio));
scope.isPlaying = false;
scope.play = function () {};
scope.stop = function () {};
}
};
}]);
在这个例子中,我们实际上会受益于模板中的 and 元素以及链接函数中的 and scope.audioSrc = attrs.playerDirective。
关于angularjs - Angular.js createElement 没有创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24373930/