我正在使用 angular.js 1.2.13。我正在使用第三方工具,该工具使用 Angular.js 并集成到我的项目中,我在 .js 文件中使用 Angular.js 代码。
为了获取范围数据,我在 HTML 元素上使用 .scope() 。它在 chrome 和 mozilla 中工作正常,但在 IE 9 上,angular.element('#someId').scope() 返回未定义。
我已经调试并发现 angular.element('#someId') 返回预期的元素,但 .scope() 返回未定义的元素。
在 angular.js 的网站上,写着 1.2.X 完美兼容 IE9。为什么我会收到此错误。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
//This code is written in external js file appConfig.js which is imported after angular.js
angular.module('modelerApp', []).run(['$rootScope', function($rootScope){
//This function is defined by me
$rootScope.bootstrap = function() {
//some logic needs to be executed here which should happen only after page load, so I am keeping it inside rootscope
}
}]);
<script type="text/javascript">
//This code is written in external js file which is getting imported in this page
$(document).ready(function(){
var scope = angular.element('#someId').scope(); //undefined
//I need scope to access rootscope of angular in order to execute logic inside bootstrap method
var rootScope = scope.$root;
//I want to execute logic written in bootstrap method, which is in $rootScope
//This logic uses angular js routes and all, and thus needs to be inside angular code.
//This has nothing to do with specific controller
rootScope.bootstrap();
});
</script>
<div ng-app="modelerApp" ng-controller="itemController">
<div id="main">
<div id="someId">
</div>
</div>
</div>
感谢任何帮助。
最佳答案
您正在尝试访问 Angular 范围之外的范围,并且您不在 Angular 的路径上,您不应该以这种方式将 Angular 与 jQuery 一起使用,而是在 Angular 之上包含 jQuery,以利用 jQuery 而不是 Angular 的 jqLite:
angular.module('modelerApp', []).controller('itemController', function($scope) {
var scope = angular.element($('#someId')).scope(); //undefined
$scope.obj = {
scopeId: scope.$id
};
//console.log(scope.$id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="modelerApp" ng-controller="itemController">
{{obj.scopeId}}
<div id="main">
<div id="someId">
</div>
</div>
</div>
A detailed post about thinking in angular if one has a jquery background.
关于javascript - angular.element ('#someId' ).scope() 在 IE 9 中返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34450556/