簡體   English   中英

從AngularJS中的指令模板訪問內聯控制器變量

[英]Acessing inline-controller variable from directive template in AngularJS

這是代表我的問題的小提琴: 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';
            }]
        }
    }])

基本上,控制器沒有名稱,因為它是一個內聯控制器,那么如何在template屬性中表示它呢? 我是否必須像下面這樣實際聲明控制器?

    .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';
            }]
        }
    }])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM