我正在做一个简单的教程而且无法通过一个非常简单的事情。
我想在页面加载时创建一个元素。我完全按照了代码。我使用谷歌浏览器。以下不会创建音频元素有什么问题?:
的index.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。
由于
答案 0 :(得分:7)
少数事情:
相反,你可以这样探索:
<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 () {};
}
};
}]);
在这个例子中,我们实际上可以在链接函数中使用和scope.audioSrc = attrs.playerDirective在模板中使用和元素。
答案 1 :(得分:1)
确定这是什么教程告诉你在控制器中创建一个DOM元素?那太错了。
据说,在javascript中创建DOM元素是不够的,你需要附加元素才能让它们出现你必须得到你想要附加它们的元素,让我们说是身体然后你做了类似
的事情 $scope.div = document.createElement("div");
angular.element(document.getElementsByTagName('body')).append( $scope.div);