私のサンプルアプリケーションをホストしましたhere MainCtrl変数にディレクティブの 'link'関数にアクセスしようとしましたが、AngularJs 1.6 - ディレクティブの 'link'関数で親スコープにアクセスできない
angular.js:14700 ReferenceError: testMessage is not defined
at Object.link (TestDirective.js:12)
at angular.js:1385
at invokeLinkFn (angular.js:10545)
at nodeLinkFn (angular.js:9934)
at angular.js:10273
at processQueue (angular.js:17051)
at angular.js:17095
at Scope.$digest (angular.js:18233)
at Scope.$apply (angular.js:18531)
at done (angular.js:12547) "<test-directive>"
私はrequirejsを使用して角度アプリを作成しました。
------------main.js-----------------
require.config{
///configuration here...
});
require(['app','angular','MainCtrl','TestDirective'],function(app,angular){
angular.bootstrap(document,['MyApp']);
});
---------------app.js-------------
define(['angular','angular-resource'],function(angular){
var ngapp = angular.module('MyApp',['ngResource']);
return ngapp;
});
-------------MainCtrl.js-----------------------
define(['app'],function(app){
app.controller('MainCtrl',function($scope){
$scope.testMessage = "Variable from MainCtrl";
})
});
------------------TestDirective.js---------------------------
define(['app'],function(app){
app.directive('testDirective',function(){
return{
restrict: 'E',
templateUrl: 'js/TestDirective.html',
link: function(scope){
scope.innerVariable = "Inner variable";
//testMessage is defined in MainCtrl
//I can access this variable in view i.e. TestDirective.html
//But can not access it below
scope.ourterVariable = testMessage;
scope.testFun = function(){
///cant access MainCtrl variable here....
}
}
}
});
});
----------------index.html------------------
<!DOCTYPE html>
<html lang="en">
<head>
<title>Heroic Features - Start Bootstrap Template</title>
<script src="node_modules/requirejs/require.js" data-main="js/main.js"></script>
</head>
<body ng-controller="MainCtrl">
{{testMessage}}
<test-directive></test-directive>
</body>
</html>
私は、このような方法でディレクティブを作成している間、私の情報を1としてMainCtrl->testMessage
にアクセスしている間、私は<test-directive>
のエラーを取得していますページをロードした後、ディレクティブは内のすべてのプロパティを継承します。このアプリhere
を開催していますMainCtrl
。
また、ディレクティブのビューではMainCtrl->testMessage
にアクセスできますが、ディレクティブのリンク機能ではアクセスできません。
助けてください。
アップデート1:
私は今、私はすべてのランタイムエラーを取得していないのですが、それでも、scope.$parent.testMessage
はundefined
ありがとう、私はそれを試みましたが、うまくいきませんでした。 'testMessage'はディレクティブの観点からアクセス可能であることに注意してください。しかし、私は 'リンク'機能でそれにアクセスすることができません。 – user2243747
リンク機能の中でスコープ$ parent.testMessageを試してみてください。 –
@AnjDあなたのご意見ありがとうございます。私はあなたの提案を組み込んだ後、元の質問を更新しました。まだ運がない.. – user2243747