簡體   English   中英

從Directives訪問AngularJS范圍

[英]Access AngularJS scope from Directives

我正在嘗試訪問app控制器中定義的范圍變量,這樣我就可以更新來自我創建的Directive的click事件,但它似乎無法從其隔離范圍訪問全局范圍。

定義了scope變量(currentTitle):

app.controller('news', function($scope, $http, $timeout) {
$scope.promise = $timeout(function() { //This is here just to mock the asynchronous loading of the data
$scope.articles = [{
  title: 'Article 1',
  content: 'It works!'
}, {
  title: 'Article 2',
  content: 'It still works'
}]
}, 3000);

$scope.currentTitle = "my - title";
$scope.showDetails = false;
});

並且指令中定義的范圍是:

scope: {
  //bind the showDetails into the scope so it can be seen by all of the accordion elements
  promise: '&?',
  currentTitle: '=?',
  showDetails: '=?bind'
}

這是一個包含所有代碼的codePen: http ://codepen.io/valecarlos/pen/bpmryw

我想要做的是更新標題標題,當點擊其中一個標題時,現在我只是試圖對范圍的currentTitle變量進行硬編碼,並且$apply -inside指令中的click事件,但我沒有看到它反映在標題的標題上。

謝謝!

嘗試在指令范圍內設置currentTitle鍵。 它將創建一個雙向綁定,允許您從指令的范圍輕松更改父控制器中的currentTitle

JS

  scope: {
    ...
    currentTitle: '=',
    ...
  },

HTML

         <accordion promise="promise" current-title="currentTitle">
            <!--<dt ng-repeat-start="article in articles" ng-class="showDetails ? 'show-titles' : 'show-titles-not'">.-->
            <dt ng-repeat-start="article in articles" ng-class="{'show-titles' : showDetails}">
            <div class="grid-30">
                <div class="round-div"></div>
            </div>
            <div class="grid-70">
                <h5>{{article.title}}</h5>
            </div>

            </dt>
            <dd ng-repeat-end="" ng-class="{'show-titles' : showDetails}">
                <div class="grid-40">
                    <img src={{article.image}} alt="">
                </div>
                <div class="grid-60">
                    <div class="news-desc">
                        <h5>
                            {{article.title}}
                        </h5>
                        <p>
                            {{article.content}}
                        </p>
                    </div>
                </div>
            </dd>
        </accordion>

如果使用“&”語法傳入函數,則應該能夠在指令中調用它。

我們假設控制器中的函數如下所示:

$scope.someFunction = function(someParameter) {...}

然后你的指令將如下所示:

...
    scope {
      someFunction: "&"
   }
...
//in link or controller
$scope.someFunction({someParameter:'foo'});

暫無
暫無

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

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