当被指令的链接功能加入,会发生什么到NG-点击和控制器访问 [英] What happens to ng-click and controller access when added by a directive's link function
问题描述
我有一个简单的jsfiddle :
<div ng-controller="MainCtrl as mainCtrl">
<div ng-show="mainCtrl.visible" ng-click="mainCtrl.swap()">Can you see me?</div>
<div see-me></div>
</div>
angular.module('AngularTestApp', [])
.controller('MainCtrl', [function () {
var self = this;
self.visible = true;
self.swap = function() {
self.visible = ! self.visible;
};
}])
.directive('seeMe', [function () {
return {
template: 'or me?',
link: function (scope, element, attrs) {
attrs.$set('ng-show', 'mainCtrl.visible');
attrs.$set('ng-click', 'mainCtrl.swap()');
}
};
}]);
由于一个范围
指令的定义对象的默认值是假
我希望家长的范围可因而对于 ATTRS $集('NG点击','mainCtrl.swap()');
来工作,但是当我点击它不火 DIV
。为什么呢?
Since the default value for a scope
on a directive's definition object is false
I would expect the parent's scope to be available and thus for attrs.$set('ng-click', 'mainCtrl.swap()');
to work, but it does not fire when I click the div
. Why?
(注:我尝试添加 $编译
按照 PPA的回答为AngularJS - 在指令中的纽带作用但没有任何效果NG-点击)
(N.B. I tried adding $compile
as per ppa's answer to 'AngularJS - ng-click in directive's link function' but that had no effect.)
推荐答案
在元素上设置属性不处理任何指令。你必须使用 $编译
服务来编译与当前的范围的新模板
并取代当前元素编译元素。
Setting attributes on an element doesn't process any directives. You'll have to use the $compile
service to compile the new template with the current scope
and replace the current element with the compiled element.
.directive('seeMe', ['$compile', function ($compile) {
return {
template: 'or me?',
link: function (scope, element, attrs) {
var newElement = $compile('<div ng-show="mainCtrl.visible" ng-click="mainCtrl.swap()">or me?</div>')(scope);
element.replaceWith(newElement);
}
};
这篇关于当被指令的链接功能加入,会发生什么到NG-点击和控制器访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!