我认为这里的问题是你仍然试图以 jQuery 风格的方式做事。这需要更 Angular 的方法。
您可以通过多种方式处理此问题,但正确的方式取决于您应用的功能/布局/样式等。
选项 1:
如果您在应用程序中使用路由/状态,您可以简单地使用带有控制器的抽象路由。在抽象路由的控制器中附加变量数据将导致嵌套路由继承该 $scope.your.variable
(app.js)
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$stateProvider
.state('exampleState', {
url: '/example',
abstract: true,
templateUrl: 'templates/example/root-view.html',
controller: 'ParentCtrl'
})
.state('stats.games', {
url: '/games',
views: {
'stats-games':{
templateUrl: 'templates/example/firstpage.html',
controller: 'PageOneCtrl'
}
}
})
.state('stats.games', {
url: '/games',
views: {
'stats-games':{
templateUrl: 'templates/example/secondpage.html',
controller: 'PageTwoCtrl'
}
})
});
(controller.js)
.controller('ParentCtrl', function($scope) {
$scope.myValues = {
value1:"some value",
value2:"some other value"
}
})
.controller('PageOneCtrl', function($scope) {
$scope.message = $scope.myValues.value1
})
.controller('PageTwoCtrl', function($scope) {
$scope.message = $scope.myValues.value2
})
(firstpage.html 或 seccondpage.html)
<ion-view view-title="First/Second Page">
<ion-content>
<div id="mainMessage">{{message}}</div>
</ion-content>
</ion-view>
选项 2:您可以制作这样的自定义指令,并将数据替换为您的需要。这个例子展示了两种修改 DOM 的方法。
.directive("mydirective", function(){
return {
template: "<h1>Hi, ...</h1>", // or use an html file here
replace: true,
restrict: 'A',
scope: false, //default
link: function(scope, element, attrs){
console.log([scope],[element],[attrs]);
console.log(scope.myValues.value1);
/// use element from here
// do something...
// element.append("hello <br>")
}
}
});
然后在你的 .html 文件中包含
<div mydirective> </div>
选项 3:这是我最喜欢在视图之间共享内容/数据的方式...AngularJS 中的服务或工厂非常棒。创建一个服务,并将其注入到模块控制器中,以便对来自多个控制器的数据进行即时共享访问:
.service("myDataService", function() {
var myData = {
dataSetOne: {
name: "John Doe",
message: "hi, John",
other: "misc info"
},{
dataSetTwo: {
name: "John Doe",
message: "hi, John",
other: "misc info"
}
}
})
然后在你的控制器中确保你包含服务和依赖注入:
.controller('yourPageCtrl', function($scope, myDataService) {
$scope.myData = myDataService;
$scope.message = "Hi "+$scope.myData.dataSetOne.name;
// do something here
});
你的 DOM 看起来像这样:
<div id"someID">{{message}} </div>
如果一切都失败了,最后也是最糟糕的选择是使用 $rootScope。我真的不推荐这种方法,因此如果需要,我会留给你研究。
希望对您有所帮助。