Angular Ui-路由器 |从控制器访问视图中的范围变量,但不工作
Angular Ui-Router | Accesing a scope variable in a view from controller, but not working
我有这个plunkr。我定义了两个控制器:mainController
和 itemsController
。我想从视图访问范围变量 items
,但我不能。
要复制,您需要先点击按钮Populate Items
,(数组项由service
填充),您会在 console
中看到这些值。然后点击按钮Say Hello !
然后你会看到items是空的;但是,正在访问变量 tab
。
我认为我没有以正确的方式应用控制器的定义。
我们需要的,是数据共享:
How do I share $scope data between states in angularjs ui-router?
所以不用这个
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.items = []; // local reference, not shared
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.items = resp;
console.log($scope.items);
});
};
})
我们将填写共享引用$scope.Model.items = resp;
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.Model.items = resp;
console.log($scope.Model.items);
});
};
})
这将挂接到超级根主页。所以,而不是这个:
$stateProvider
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html"
}
}
});
我们将拥有:
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html",
// HERE we do the magic
// this is a super parent view
// at which $scope we will have shared reference Model
controller: function($scope){
$scope.Model = {}
}
}
}
});
实际查看 here
我有这个plunkr。我定义了两个控制器:mainController
和 itemsController
。我想从视图访问范围变量 items
,但我不能。
要复制,您需要先点击按钮Populate Items
,(数组项由service
填充),您会在 console
中看到这些值。然后点击按钮Say Hello !
然后你会看到items是空的;但是,正在访问变量 tab
。
我认为我没有以正确的方式应用控制器的定义。
我们需要的,是数据共享:
How do I share $scope data between states in angularjs ui-router?
所以不用这个
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.items = []; // local reference, not shared
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.items = resp;
console.log($scope.items);
});
};
})
我们将填写共享引用$scope.Model.items = resp;
app.controller("itemsController",
function($rootScope, $scope, $state, $stateParams, Data) {
$scope.getFromJson = function() {
Data.get().then(function handleResolve(resp) {
$scope.Model.items = resp;
console.log($scope.Model.items);
});
};
})
这将挂接到超级根主页。所以,而不是这个:
$stateProvider
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html"
}
}
});
我们将拥有:
.state("home", {
abtract: true,
url: "/home",
resolve: {
$title: function() {
return 'Tab1';
}
},
views: {
"viewA": {
templateUrl: "home.html",
// HERE we do the magic
// this is a super parent view
// at which $scope we will have shared reference Model
controller: function($scope){
$scope.Model = {}
}
}
}
});
实际查看 here