AngularJS指令范围属性不在指令视图中呈现

时间:2017-03-05 23:07:45

标签: angularjs angularjs-directive angularjs-scope

我的指令的scope属性存在问题,它不能渲染到想要在指令视图中呈现。

app.js

.config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })

main.js

angular.module('todayfmApp')
    .controller('MainCtrl', ['$scope', function ($scope) {

        this.formsetup = [];

        this.formsetup.title = "Find Your Break";

    }]);

mainController视图 - 表单设置:{{main.formsetup.title}}正确呈现

<h2>Form Setup: {{main.formsetup.title}}</h2>
<section class="home-banner">

    <carousel-partial></carousel-partial>

    <overlay-form formsetup="main.formsetup.title"></overlay-form>

指令

angular.
    module('directives').
    directive('overlayForm', function() {
        return {
            restrict: 'E',
            scope: {
                formsetup: '='              
            },
            controller: [ '$http', '$scope',
                function OverlayFormController($http, $scope) {

                    var self = this;

                    self.getResponseData = function(){
                        $http.get('data/form-data.json').then(function(response) {
                            self.formdata = response.data;                          
                        });
                    }

                    this.logResponseData = function() {
                        console.log(self.formdata);
                    }

                    this.getResponseData();
                }
            ],
            controllerAs: 'Ctrl',
            bindToController: true,
            templateUrl: 'scripts/directives/overlay-form/overlay-form.template.html',
        };
    });

指令视图

<div class="overlay-form">
  <h3>{{formsetup.title}}</h3>

1 个答案:

答案 0 :(得分:1)

问题在于模板绑定。它应该是:(当你使用控制器时,你需要使用别名来引用视图元素)

<div class="overlay-form">
  <h3>{{Ctrl.formsetup.title}}</h3>
</div>

指令HTML代码应为:

<overlay-form formsetup="main.formsetup"></overlay-form>

请查看Plunker以了解其工作原理。