所以,我不确定我在问什么,但我想实现这个:
索引.html:
<div ng-view>
</div>
<script>
angular.module('myApp', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', { controller: "HomeController", templateUrl: '/Partials/Home/Dashboard.html' });
$routeProvider.otherwise({ redirectTo: '/' });
}]);
</script>
首页/Dashboard.html:
<h2 class="page-header">{{welcome}}</h2>
<!-- Insert my reusable component here -->
我的可重用组件将驻留在 MyComponent/Component.html
中,并有与之关联的 Controller myApp.component.controller
。
实际上,我想将可重用组件放入页面并将其绑定(bind)到我的 Controller 。所以我得到了这个:
.directive('MyComponent', function() {
return {
restrict: 'E',
scope: {
},
templateUrl: '/MyComponent/Component.html'
};
});
那么我现在如何将我的 Controller 绑定(bind)到它呢?我是否这样做:
.directive('MyComponent', function() {
return {
restrict: 'E',
resolve: function () {
return /* resolve myApp.component.controller */;
},
templateUrl: '/MyComponent/Component.html'
};
});
最佳答案
当一个指令需要一个 Controller 时,它接收那个 Controller 作为它的第四个参数 链接功能。
.directive('MyComponent', function() {
return {
restrict: 'E',
controller: 'MyController', // attach it.
require: ['MyController','^ngModel'], // required in link function
templateUrl: '/MyComponent/Component.html',
link: function(scope, element, attrs, controllers) {
var MyController = controllers[0];
var ngModelCtlr = controllers[1];
///...
}
};
});
^ 前缀意味着该指令在其父元素上搜索 Controller (没有 ^ 前缀,该指令将仅在其自己的元素上查找 Controller )。
最佳实践:当您想向其他指令公开 API 时使用 Controller 。否则使用链接。
关于javascript - 将 Angular Controller 应用于模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26404112/