我正在使用 ui-router 进行路由,并且将使用嵌套范围,因此希望使用“controller as”语法。但是,我无法找出正确的语法/组合来访问我 View 中的 Controller 对象属性。
app.js(设置路由)
(function() {
angular
.module('ICP_App', ['ui.router', 'satellizer', 'ngMaterial', 'ngMessages', 'xeditable'])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$urlRouterProvider.otherwise('dashboard');
$stateProvider
.state('clients', {
url: '/clients',
templateUrl: '../partials/clients-index.html',
controller: 'ClientsController as ClientsCtrl'
})
// more routes here...
})();
ClientsController.js
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
var vm = this;
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
});
})();
index.html
<body ng-app="ICP_App" ng-cloak>
<!-- sidebar, header etc -->
<div ui-view></div> <!-- pull in view -->
</body>
最后,clients-index.html
部分
<div class="content">
<div class="pane" ng-repeat="client in clients">
{{ client.name }}
</div>
</div>
我也尝试过vm.clients中的client
,但没有成功。
我的 Controller as 语法有问题吗?因为我在 ui-router 代码中使用 Controller ,但在创建 Controller 时不再使用 Controller 。如果我在 Controller 中再次使用 Controller ,则会出错(Argument ClientsController is not a
)。
我应该指出,控制台日志记录 vm.clients 确实为我提供了控制台中的数据,但我似乎无法在我的 View 中访问它。
提前致谢。
最佳答案
如下修改您的ClientsController
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
var vm=this;
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
}); })();
修改client-index.html如下
<div class="content">
<div class="pane" ng-repeat="client in ClientsCtrl.clients">
{{ client.name }}
</div>
下面的链接将帮助您更深入地理解 Controller 语法
https://toddmotto.com/digging-into-angulars-controller-as-syntax/
关于javascript - 无法使用 UI 路由器和 'controller as' 语法访问 View 中的 Controller 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807617/