Angularjs 如何让angular指令在每次访问视图时执行,而不刷新页面
我创建了一个自定义指令,它包装了一个jquery函数,该函数将html转换为一个用户可以输入标记的位置(类似于SO标记功能) 这是我的指令代码:Angularjs 如何让angular指令在每次访问视图时执行,而不刷新页面,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我创建了一个自定义指令,它包装了一个jquery函数,该函数将html转换为一个用户可以输入标记的位置(类似于SO标记功能) 这是我的指令代码: App.directive('ngTagItWrapper', function ($resource, rootUrl) { $("#myTags").tagit({ allowSpaces: true, minLength: 2, tagSource: function (search, showChoices) {
App.directive('ngTagItWrapper', function ($resource, rootUrl) {
$("#myTags").tagit({
allowSpaces: true,
minLength: 2,
tagSource: function (search, showChoices) {
$.ajax({
url: rootUrl + "/api/Tag?searchTerm=" + search.term,
data: search,
success: function (choices) {
choices = $.map(choices, function (val, i) {
return val.Name;
})
showChoices(choices);
}
});
}
});
return {}
});
当我第一次导航到包含该指令的视图时,该指令触发,该指令将ul
html元素转换为我需要的内容。但是,如果我单击站点的另一部分,然后单击返回到站点中包含标记输入屏幕的部分,则该指令永远不会触发,html也不会转换为我可以输入标记的好位置
以下是查看代码:
<p>Hint: <input ng-model="knowledgeBit.Hint" /></p>
<p>Content: <input ng-model="knowledgeBit.Content"/></p>
<ul id="myTags" ng-tag-it-wrapper>
</ul>
<button ng-click="saveKnowledgeBit()">Save</button>
提示:
内容:
拯救
如果我刷新页面,该指令将触发,我将获得标记输入区域。所以基本上angular不知道再次启动指令,除非我完全重新加载站点。有什么想法吗?指令构造函数只运行一次,然后$compile缓存返回的定义对象 您需要的是将代码放入链接函数中:
谢谢宜兰!noob note--“elm”在上面的代码中指的是要转换的html元素,出于我的目的,我使用jquery选择它`$(“#myTags”)。tagit()如果将指令放在同一个元素上,您已经有了对它的jquery包装器的引用,请检查
elm===$(“#myTags”)
,如果没有,那么您需要将jquery的脚本放在angular的脚本之前。
App.directive('ngTagItWrapper', function ($resource, rootUrl) {
return {
link: function(scope, elm){
elm.tagit({
allowSpaces: true,
minLength: 2,
tagSource: function (search, showChoices) {
$.ajax({
url: rootUrl + "/api/Tag?searchTerm=" + search.term,
data: search,
success: function (choices) {
choices = $.map(choices, function (val, i) {
return val.Name;
})
showChoices(choices);
}
});
}
});
}
}
});