我是 angularjs 的新手。在处理 AngularJS 中的指令时,我遵循了 AngularJS 指令一书中的示例。从那里我尝试了一些示例,但我坚持使用其中一个示例,我需要在我的应用程序中实现类似的东西。
代码是:
<html>
<head>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="directiveapp">
<!-- Two way binding -->
<div ng-init="title = 'Hello World'; subtitle = 'I am an app'">
<h2 id="appTitle">{{title}}</h2>
<h3 id="appSub">{{subtitle}}</h3>
<button id="newAppTitle" ng-click="setAppTitle('App 2.0')">Upgrade me!</button>
<div my-scoped-directive msd-title="I'm a directive, within the app{{title}}" msd-subtitle="subtitle">
<h4 id="directiveTitle">{{title}}</h4>
<button id="newDirTitle" ng-click="setDirectiveTitle('bob')">Bobit!</button>
<button id="newDirSub" ng-click="setDirectiveSubtitle('Time to submerge')">Empty the ballasts!</button>
</div>
</div>
</div> <!-- End of directiveApp -->
</body>
</html>
script.js
var app = angular.module('directiveapp', []);
app.directive('myScopedDirective', function() {
return {
restrict: 'EA',
scope : {
'title' : '@msdTitle',
'subtitle' : '=msdSubtitle'
},
link : function ($scope, $element, $attrs) {
console.log($scope)
$scope.setDirectiveTitle = function (title) {
$scope.title = title;
};
$scope.setDirectiveSubtitle = function (subtitle) {
$scope.subtitle = subtitle;
};
}
};
});
问题是当我单击按钮时没有单击事件触发。文本没有改变。 单击 Bobit 按钮后,文本应从 Hello world 更改为 I'm a 指令,在应用程序 Hello World 内
我在这里附上插件链接:http://plnkr.co/edit/NdnWDqr9XCph6uNvJwlc?p=preview
最佳答案
这不是正确的方法,因为应用于元素的指令被编译为指令,但在该元素内部没有指令的范围,它包含 Controller 的范围。 app.js
var app = angular.module('directiveapp', []);
app.directive('myScopedDirective', function() {
return {
restrict: 'EA',
scope : {
'title' : '@msdTitle',
'subtitle' : '=msdSubtitle'
},
templateUrl:'main.html',
link : function ($scope, $element, $attrs) {
console.log($scope)
$scope.setDirectiveTitle = function (title) {
$scope.title = title;
};
$scope.setDirectiveSubtitle = function (subtitle) {
$scope.subtitle = subtitle;
};
}
};
});
查看更新后的 plunkr link
关于javascript - 按钮单击上的隔离范围不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31403123/