11

これは私のアプリの設定です:

angular.module('myApp', ['myApp.directives', 'myApp.controllers', 'myApp.services']);

これは私のコントローラーです:

angular.module('myApp.controllers', [])
  .controller('MainCtrl', function ($scope) {
      $scope.name = 'world';
  });

これは私の指示です:

var directives = angular.module('myApp.directives', []);

directives.directive("hello", function () {
    return function (scope, elm, attrs) {
        elm.text("hello, " + scope[attrs.name]);
    };
});

これは私のhtmlです:

<div ng-controller="MainCtrl">
    <h1 hello></h1>
</div>

問題は、Angular がディレクティブを次のようにレンダリングすることです。

こんにちは、未定義

それ以外の:

こんにちは世界

なにが問題ですか?

4

4 に答える 4

3

を使ってアクセスできますscopehttp://jsfiddle.net/rPUM5/を見てください

directives.directive("hello", function () {
    return function (scope, elm, attrs) {
        elm.text("hello, " + scope.name);
    };
});​
于 2012-12-24T15:08:57.947 に答える
1

別のケースを見つけました:

Ajax リクエスト本文からの変数にアクセスしている場合は、変数が設定されるまで待機する必要があります。

例えば:

# in controller
$http.get('/preview').then( (response) ->
  $scope.tabs = response.data.tabs
  $scope.master_switch = '1'
  console.info 'after get response in controller'
)

# in directive
directive('masterSwitch', ->
  (scope, element, attrs) ->
    alert 'in directive!'   # will show before "after get response in controller"
    console.info scope.master_switch  # is undefined
    setTimeout( -> console.info(scope.master_switch), 50) # => 1
于 2013-08-06T01:34:58.030 に答える