我阅读了这个链接:AngularJS访问范围来自js函数外部,我试图访问控制器,但我没有设置索引。类似fiddlejs示例的html。
我将我的应用程序设置为使用$routeProvider,并设置了一个简单的服务来共享一些应用程序数据。我希望能够在控制器之间进行通信,并使用该服务进行通信。但我的一条路线遇到了问题,因为我希望能够将一些应用程序数据从页面设置到服务。
signin.html有一堆使用一些javascript小部件的javascript,它们一旦完成就会有回调。我试图从脚本调用我的LoginController中的方法,但我得到一个未定义的,因为我没有用ng控制器指定控制器。有没有办法从我的signin.html?脚本到LoginController
我的应用程序。js
var myApp = angular.module('myApp', ['ngCookies', 'ngResource'],
function ($routeProvider, $locationProvider, $httpProvider) {
});
myApp.service('sharedPropertiesService', function () {
var isValidUser = false;
return {
setValidUser: function (userValid) { isValidUser = userValid;},
isValidUser: function () {return isValidUser;},
};
});
myApp.controller('loginController', ['$scope', '$http', 'sharedPropertiesService',
function ($scope, $http, sharedPropertiesService) {
$scope.test = function() {alert('called from inside the html template.');};
}
]).controller('PageController', ['$scope', '$location', 'sharedPropertiesService',
function ($scope, $location, sharedPropertiesService) {
if (sharedPropertiesService.isValidUser()) {
$location.path('/myapp');
} else {
// Have them login
$location.path('/signin/');
}
}
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: '/home.html', controller: 'PageController'}).
when('/signin', {templateUrl: '/signin.html', controller: 'SusiController'}).
when('/myap', {templateUrl: '/myApp.html', controller: 'PageController'});
}]);
指数html
<html ng-app="myApp">
<head>
// load Angularjs, jquery, etc.
</head>
<body>
<div id='myapp' ng-view ng-cloak></div>
</body>
</html>
signin.html
<div id="loginwidget">
<div role="main" id="content" >
<div id="signIn" >
</div>
<div>
<div>
<script>
$.ready('loginwidget_main', function () {
loginwidget.load('signin', function () {
done : success,
fail : fail
});
});
function success() {
var scope = angular.element($('#myapp')).scope().test;
alert(scope); // this shows undefined
scope();
}
function fail() {alert("failed to login");}
</script>
我在朋友的帮助下找到了答案。以下是解决方案:
在签到处。html文件将id添加到顶部的div中。在脚本代码中,使用该id使用jquery访问作用域(不需要使用angular.element()。
signin.html
<div id="loginwidget">
<div role="main" id="content" >
<div id="signIn" >
</div>
<div>
<div>
<script>
$.ready('loginwidget_main', function () {
loginwidget.load('signin', function () {
done : success,
fail : fail
});
});
function success() {
var scope = $('#loginwidget').scope();
scope.test();
}
function fail() {alert("failed to login");}
</script>
You can check below code snippet here we are calling the loginwidget scope function in javascript function.
<div id="parentController" ng-controller="parentController">
<div id='myapp' ng-view ng-cloak></div>
</div>
function myFunction(){
angular.element(document.getElementById('parentController')).scope().myFunction();
}
注意:在这里您需要定义您的函数的父母控制器。