很抱歉,如果它已经发布,但我找不到它,也无法更清楚地写出问题。
我正在尝试获取html对象的实例并将其用作angularJs中的变量,这里有一个示例来说明它
<div id="whatever" class="donotcare" data-ng-init=doSomething(htmlobject)>blabla bla</div>
$scope.doSomething = function(){
console.log("the div object is there")
}
基本上,我要做的是获取div并将其作为变量传递,以便我可以使用angularjs获取其id,其内容......
当你点击它很容易,只需获取$ event然后在javascript上获取currentTarget。但我想要的是它在加载时运行。 希望你理解
答案 0 :(得分:0)
对我的代码做了一些修改。关键在于,当发生交互时,例如单击并将事件obj传递给函数。
不确定你究竟是什么意思。但是下面的代码可以帮助你:
HTML code:
this.doSomething = function(evt) {
console.log(evt.currentTarget);
}
控制器代码:
<?php $path = "http://host/images"; ?>
<img src="<?=$path."/id-14.png" ?>" alt="[profile picture]">
答案 1 :(得分:0)
您需要使用装饰器指令 -
在您的情况下,您可以创建一个新的装饰器指令,并使用链接功能中的以下代码来获取正文的句柄 -
link : function(scope, el, attrs){
//you code will go here using $('body')
}
答案 2 :(得分:0)
根据doSomething()
的定义位置,您可以选择以下选项之一:
选项#1
如果您在全局范围内的某处定义了doSomething()
,则可以尝试编写自己的角度指令app-init
而不是ng-init
,并将您想要的函数名称传递给它致电(在您的情况下为doSomething
)。这个函数将接收DOM元素(html对象,就像你所说的那样)并随意使用它,例如提醒id。
function doSomething(obj) {
alert(obj && obj.id);
}
angular
.module('app',[])
.directive('appInit', ['$window', function($window) {
return {
link: function(scope, element, attrs) {
$window[attrs.appInit](element[0])
}
}
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div id="whatever" class="donotcare" app-init="doSomething">blabla bla</div>
</div>
&#13;
选项#2
如果您在其中一个父作用域中定义了doSomething()
,则可以执行以下操作:
angular
.module('app',[])
.run(function($rootScope) {
$rootScope.doSomething = function doSomething(obj) {
alert(obj && obj.id);
}
})
.directive('appInit', function() {
return {
scope: { appInit: '&' },
link: function(scope, element) {
scope.appInit({element: element[0]})
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div id="whatever" class="donotcare" app-init="doSomething(element)">blabla bla</div>
</div>
&#13;
有关如何在指令中使用&
绑定的更多信息,请访问:https://docs.angularjs.org/api/ng/service/$compile
<强> ngInit 强>
如果您查看AngularJS source code,您会发现实际上ng-init
代码几乎相同:
var ngInitDirective = ngDirective({
priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});