从AngularJS中的指令模板访问内联控制器变量

Acessing inline-controller variable from directive template in AngularJS

本文关键字:访问 控制器 变量 AngularJS 指令      更新时间:2023-09-26

这是一个代表我的问题的小提琴:https://jsfiddle.net/m9t7ew8j/1/

代码的重要部分如下:

   .directive('firstDirective', [function () {
        return {
            restrict: 'E',
            template: '<div>This is a directive.
                        Here is a scope variable
                        pre-defined: {{name}} </div>', // <---- this is the problem
            controller: ['$q', function ($q) {
                var vm = this;
                vm.name = 'something';
            }]
        }
    }])

基本上,控制器没有名称,因为它是一个内联控制器,那么我如何在模板属性中表示它呢?我真的必须像下面这样声明控制器吗?

    .controller('secondController', [function(){
        var vm = this;
        vm.name = 'John Snow';
    }])
    .directive('secondDirective', [function(){
        return {
        restrict: 'E',
        template: '<div>This is a directive.
                   Here is a scope variable
                   pre-defined: {{vm.name}} </div>', // <- declaring as vm.name will work
        controller: 'secondController as vm'
      }

我认为在您的控制器中,您希望获得$scope并将变量分配给$scope

.directive('firstDirective', [function () {
        return {
            restrict: 'E',
            template: '<div>This is a directive.
                        Here is a scope variable
                        pre-defined: {{name}} </div>',
            controller: ['$scope','$q', function ($scope,$q) {
                $scope.name = 'something';
            }]
        }
    }])

演示:http://plnkr.co/edit/uzudOphRL8QO6utEBF4F?p=preview

从使用this 实现

.directive('firstDirective', [function () {
        return {
            restrict: 'E',
            template: '<div>This is a directive.
                        Here is a scope variable
                        pre-defined: {{vm.name}} </div>',
            controllerAs: 'vm',
            controller: ['$q', function ($q) {
                var vm = this;
                vm.name = 'something';
            }]
        }
    }])