为什么在这个脚本中:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module( "test", [] );
app.run(
angular.element.prototype.test = function ( ) {
alert ( "da" );
}
);
app.directive('cacat', function() {
return {
restrict: 'E',
link: function (scope, element, attrs) {
}
};
});
</script>
</head>
<body ng-app="test">
<cacat></cacat>
</body>
</html>
功能测试叫什么? 我希望仅在需要时调用此函数。
回答
app.run(
function () {
angular.element.prototype.test = function ( ) {
alert ( "da" );
}
}
);
最佳答案
赋值语句可以被评估为它们的值。 如果你做类似的事情
var x = false;
if(x = true) { /*Some code here*/ }
x
在 if
语句中被赋值,然后求值。
在你的样本中,
app.run(angular.element.prototype.test = function ( ) {
alert ( "da" );
})
评估您分配给 angular.element.prototype.test
的函数,有效地将函数传递给 app.run()
。 app.run()
获取它并运行它,正如人们所期望的那样。
如果您只是想让它在run()
执行中进行赋值,您需要向它传递一个执行以下操作的函数那个,像这样:
app.run(function(){
angular.element.prototype.test = function ( ) {
alert ( "da" );
});
});
关于javascript - AngularJS运行执行功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686581/