gpt4 book ai didi

angularjs - Angular Controller 和 controllerAs 指令中的关键字用法

转载 作者:行者123 更新时间:2023-12-01 02:00:13 24 4
gpt4 key购买 nike

学习 angular,所以在阅读关于 angular 的文章时,有时事情不清楚。在这里,我坚持了解此 的用途或重要性是什么。关键字 Controller 和 controllerAs 在指令 中.

代码取自此处 http://blog.thoughtram.io/angularjs/2015/01/02/exploring-angular-1.3-bindToController.html

app.controller('SomeController', function () {
this.foo = 'bar';
});

app.directive('someDirective', function () {
return {
restrict: 'A',
controller: 'SomeController',
controllerAs: 'ctrl',
template: '{{ctrl.foo}}'
};
});

我想知道这两个关键字在指令中的重要性,它们是 controller: 'SomeController', and controllerAs: 'ctrl',
如果我们不使用这两个关键字,请告诉我 controller: 'SomeController', and controllerAs: 'ctrl',那么会发生什么或者会更糟?

请帮助我了解此关键字的用法或重要性 controller: 'SomeController', and controllerAs: 'ctrl', in directive.谢谢

最佳答案

您需要 controller如果您打算引用 Controller 对象。这就是你如何连接它。
controllerAs允许你创建一个变量,你可以引用 Controller 来代替使用 $scope .

精答:

<html ng-app="app">

<head></head>

<body>
<script src="node_modules/angular/angular.js"></script>
<script>
var app = angular.module('app', []);
app.directive('fooDirective', function() {
return {
restrict: 'A',
controller: function($scope) {
// No 'controllerAs' is defined, so we need another way
// to expose this controller's API.
// We can use $scope instead.
$scope.foo = 'Hello from foo';
},
template: '{{foo}}'
};
});

app.directive('barDirective', function() {
return {
restrict: 'A',
controller: function() {
// We define a 'vm' variable and set it to this instance.
// Note, the name 'vm' is not important here. It's not public outside this controller.
// The fact that the 'controllerAs' is also called 'vm' is just a coincidence/convention.
// You could simply use 'this.bar' if you prefer.
var vm = this;
vm.bar = 'Hello from bar';
},
// This allows us to reference objects on the controller's instance by
// a variable called 'vm'.
controllerAs: 'vm',
// Now we can reference objects on the controller using the 'controllerAs' 'vm' variable.
template: '{{vm.bar}}'
};
});
</script>

<div foo-directive></div>
<div bar-directive></div>
</body>

</html>

关于angularjs - Angular Controller 和 controllerAs 指令中的关键字用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37254848/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com