【问题标题】:Angularjs: Updating a directive scope variable from controller not workingAngularjs:从控制器更新指令范围变量不起作用
【发布时间】:2014-02-17 22:15:50
【问题描述】:

我是 的新手,尝试执行更新我在调用控制器的指令中设置的范围变量的简单任务时遇到了一些麻烦。

所以我有一个指令:

app.directive('pageShell', function (){
    return{
        restrict: 'AE',
        transclude: true,
        replace: true
        scope:{
            title: '@',
            body: '@',
            footer: '@'
        },
        template: '<div class="title-content">{{title}}</div>' +
                  '<div class="body-content">{{body}}</div>' +
                  '<div class="footer-content">{{footer}}</div>'
    }
});

所以在我的 html 中:

<page-shell title="Header" body="this is my body" footer="Footer" />

在我的控制器中:

app.c

ontroller("myCtrl", function ($scope) {

    // TEST 1 - simple scope change
    // switch pages or content so change some values
    if(pageIndex === 2) {
      $scope.title = "Page 2 title";
      $scope.body = "Page 2 body content";
      $scope.footer = "Page 2 footer";
    }

    // TEST 2 - change by using apply
    $scope.$apply(function() {
            $scope.title = "Page 2 title";
            $scope.body = "Page 2 body content";
            $scope.footer = "Page 2 footer";
    });
});

所以我尝试在我的控制器中认为我应该可以访问我范围内的变量以直接更改它,但它不起作用但没有引发任何错误。尝试使用$apply,但得到错误$apply is already in progress?尝试使用 = 而不是 @ 作为标题、正文和页脚在范围内更改为双向绑定,但得到 $parse:syntax 错误。

任何线索为什么这个简单的任务不起作用?谢谢!

【问题讨论】:

  • 如果你得到一个“Apply already in progress”,这意味着你在 Angular 已经在应用更改的地方运行应用程序。可能这意味着这里发生了其他事情!你能用你的代码发布一个小提琴来证明这个问题吗?
  • 请修正您的代码格式,使其易于阅读。也请在html中提供指令声明。

标签: angularjs angularjs angularjs-directive angularjs-scope


【解决方案1】:

想通了: 我的 pageShell 指令的范围需要是:

scope:{
    title: '=',
    body: '=',
    footer: '='
},

绑定必须是双向的。

html:

<page-shell title="Header" body="this is my body" footer="Footer" />

和控制器:

Controller("myCtrl", function ($scope) {

    // TEST 1 - simple scope change
    // switch pages or content so change some values
    if(pageIndex === 2) {
      $scope.title = "Page 2 title";
      $scope.body = "Page 2 body content";
      $scope.footer = "Page 2 footer";
   }

   // TEST 2 - change by using apply
   $scope.$apply(function() {
   $scope.title = "Page 2 title";
   $scope.body = "Page 2 body content";
   $scope.footer = "Page 2 footer";
  });
});

【讨论】:

    【解决方案2】:

    你的 HTML 应该是这样的

    &lt;page-shell title="{{title}}" body="{{body}}" footer="{{footer}}" /&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多