2017-03-24 28 views
1

我有下面的代碼,但我無法工作,我想從「子」指令傳遞一個簡單的字符串到「父」指令。這裏是http://jsfiddle.net/fpax1hx7/來自孩子的角度嵌套指令傳遞值

HTML:

<div ng-app=myApp> 
    <div ng-controller=MyCtrl> 
    <directive1></directive1> 
    </div> 
</div> 

的JavaScript:

'use strict'; 
angular.module('myApp', []) 
    .controller('MyCtrl', ['$scope', function ($scope) { }]) 
.directive('directive1', function() { 
    return { 
    restrict: 'E', 
    scope: { stringtest: '=' }, 
    template: '<directive2 stringtest="stringTest"></directive2>', 
    link: function (scope, element, attrs) { 
     console.log(scope.stringTest); 
    } 

    } 
}) 
.directive('directive2', function() { 
    return { 
     restrict: 'E', 
     scope: { stringTest: '=' }, 
     link: function (scope, element, attrs) { 
     scope.stringtest="This is a Test"; 
     } 
    } 
}]); 

回答

0

有一個錯字。您正在使用stringtest,而不是stringTest和你不傳遞任何模型directive1

'use strict'; 
 
angular.module('myApp', []) 
 
    .controller('MyCtrl', ['$scope', function($scope) { 
 
    console.log('from controller'); 
 
    }]) 
 
    .directive('directive1', function() { 
 
    return { 
 
     restrict: 'E', 
 
     scope: { 
 
     stringTest: '=' 
 
     }, 
 
     template: '<directive2 string-test="stringTest"></directive2>', 
 
     link: function(scope, element, attrs) { 
 
     console.log('from directive1'); 
 
     console.log('string test from directive 1:' + scope.stringTest); 
 
     scope.$watch('stringTest', function(nv, ov) { 
 
      if (nv !== ov) { 
 
      console.log('string test from directive 1 after directive2 scope binded:' + scope.stringTest); 
 
      } 
 
     }); 
 
     } 
 

 
    } 
 
    }) 
 
    .directive('directive2', function() { 
 
    return { 
 
     restrict: 'E', 
 
     scope: { 
 
     stringTest: '=' 
 
     }, 
 
     link: { 
 
     pre: function(scope) { 
 
      scope.stringTest = "This is a Test"; 
 
     }, 
 
     post: function(scope, element, attrs) { 
 
      console.log('from directive2'); 
 
     } 
 
     } 
 
    } 
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app=myApp> 
 
    <div ng-controller=MyCtrl> 
 
    <directive1 string-test="sample"></directive1> 
 
    {{sample}} 
 
    </div> 
 
</div>

+0

感謝您對您的答覆,我可以把警報stringTest內部指令1,它仍然有效? – user865780

+0

更新了代碼。您可以看到執行順序以及指令作用域綁定的工作方式。如果你得到你期望的答案,請將此標記爲解決方案:) –

+0

它在我的工作,但我必須將第三個參數$ watch設置爲true,但它也給我「非法調用」錯誤。 – user865780