我创建了一个加载模板的简单指令。在模板中是绑定到我希望在<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>CameraDemoApp</title>
<!-- CameraDemoApp references -->
<link href="css/index.css" rel="stylesheet" />
</head>
<body>
<h2>Hello, world!</h2>
<input id="btnTakePhoto" type="button" value="Take a Photo" />
<p id="lastPhoto"></p>
<!-- Cordova reference, this is added to your app when it's built. -->
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
</body>
</html>
上触发的控制器中的函数。
指令:
ng-click
控制器:
angular
.module('myApp')
.directive('someDirective', someDirective);
function someDirective() {
var directive = {
templateUrl: 'app/components/some-directive/some-directive.html',
controller: 'MyCoolController',
controllerAs: 'vm',
restrict: 'A',
};
return directive;
}
模板:
angular
.module('myApp')
.controller('MyCoolController', MyCoolController);
function MyCoolController() {
var vm = this;
function clickMe() {
alert('clicked!');
}
cm.clickMe = clickMe;
}
我的问题是,点击<div my-cool-directive>
<a href="#" ng-click="vm.clickMe()">Click me</a>
</div>
时,ng-click
事件未触发。
答案 0 :(得分:2)
问题是我缺乏理解指令如何继承范围。将scope: true
添加到指令映射会更正我的用例范围。
angular
.module('myApp')
.directive('someDirective', someDirective);
function someDirective() {
var directive = {
templateUrl: 'app/components/some-directive/some-directive.html',
controller: 'MyCoolController',
controllerAs: 'vm',
scope: true, // <-------- Gotcha!
restrict: 'A',
};
return directive;
}
指令有3种不同类型的范围:
有关详细信息,请参阅此帖子:Understanding scopes in AngularJS custom Directives