我使用控制器作为方法而不是 $scope。我在从 HTML 调用方法时遇到一些问题。那么,问题是,这种方法中的声明和调用函数有多少种方法。
首先:(如果我首先想做某事)
var vm= this ;
vm.dataOne=[];
function funcOne() {
myService.serviceFunc()
.then(function (response) {
vm.dataOne= response.data;
});
};
function activate() {
funcOne();
}
activate();
Run Code Online (Sandbox Code Playgroud)
第二:(如果我想根据函数返回值初始化变量)
vm.dataTwo = function () {
doSomeThing();
}
Run Code Online (Sandbox Code Playgroud)
如何在控制器中定义一个从 HTML 调用的函数,如
ng-click = "ctrl.dataTwo()";
Run Code Online (Sandbox Code Playgroud)this任何人都可以向我解释以下场景吗?
ng-controller="Parent as thus"
Run Code Online (Sandbox Code Playgroud)
ng-controller="Parent as this"
Run Code Online (Sandbox Code Playgroud)
使它成为关键字的单个字母 - 我想要 - 破坏了森林。
为什么是这样?
PS 我知道这个vm约定,但我发现它干扰了控制器/视图模型的可移植性。
我有以下config和controllers
.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'page-home.html',
controller: 'homeController',
controllerAs: 'hctrl'
})
.when('/about', {
templateUrl: 'page-about.html',
controller: 'aboutController',
controllerAs: 'actrl'
})
.when('/contact', {
templateUrl: 'page-contact.html',
controller: 'contactController',
controllerAs: 'cctrl'
});
})
.controller('homeController', function(){
this.pageClass = 'page-home'
})
.controller('aboutController', function(){
this.pageClass = 'page-about'
})
.controller('contactController', function(){
this.pageClass = 'page-contact'
});
Run Code Online (Sandbox Code Playgroud)
我的问题出现在我使用的时候index.html.
<div class="page {{pageClass}}" ng-view></div>
Run Code Online (Sandbox Code Playgroud)
由于我没有使用$scope,只是写作{{pageClass}}不起作用.我怎样才能使用controller as syntax?
编辑
我有几个很好的答案.我还发现了另一种方法,如果你希望把你做这个controllerAs有不同的名称值:hctrl, actor并ctrl(像我上面的代码):
你可以在html中这样做:
<div …Run Code Online (Sandbox Code Playgroud) 观看回复时遇到问题.
我有一个SettingsCtrl作为设置,这是我的观点:
<input type="text" class="form-control" ng-model="settings.test.one" />
<input type="text" class="form-control" ng-model="settings.test.second" />Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {
var vm = this;
settingsFactory.test().then(function(response){
vm.test = response;
})
///// OR
vm.test = Test; // this is from ui-router resolve
$scope.$watch(angular.bind('vm', function () {
return vm.test;
}), function (newV, oldV) {
console.log(newV, oldV);
});
$scope.$watch(function watch(scope){
return vm.test;
}), function handle(newV, oldV) {
console.log(newV, oldV);
});
$scope.$watch('vm', function (newVal, oldVal) {
console.log('newVal, oldVal', newVal, oldVal);
});
});Run Code Online (Sandbox Code Playgroud)
我一直在寻找并找到了不同的解决方案,但没有解决方案.
****它只是第一次观看,当控制器加载并且我看到我的控制台日志时,但是当我尝试进行更改时,观察者什么都不做.
我做错了什么?