Вопрос

I am new to AngularJs. I have a route configured to a controller and a template. In the template I am calling a custom directive. The custom directive loads a partial file in which I need to fetch the scope which is set by the controller. How can I pass the scope from the directive to the partial so that the partial file can consume the scope data.

Kindly let me know how to get this implemented in AngularJs

Code snippet inside the link function of the directive:

myApp.directive('basicSummary', function() {
  return {
    restrict: 'E',
    replace:'true',
    templateUrl: "partials/basicSummary.html",
    link: function(scope, elem, attrs) {
      console.log(scope.testURL);
    }
  }
});

Output on the console is : undefined

Update: I found the root cause of why the variable was not getting initialized. The issue, is that the variable is being fetched by making an ajax call in the controller and by the time the ajax call is completed and the variable is put inside the scope inside the controller, the partial file is already loaded and hence I am getting the value of the variable inside the directive as undefined.

How can I make sure that only on success of the http call, I load the partial and the directive?

Adding the jsfiddle link: http://jsfiddle.net/prashdeep/VKkGz/

Это было полезно?

Решение

You could add a new variable to your scope in the definition of your directive to create a two-way binding, that you could safely watch for changes (for use in Javascript once the variable has been populated via ajax), and in your template use ng-show to show/hide based on whether or not the variable is defined. See this JSFiddle for an example of how that would work: http://jsfiddle.net/HB7LU/3588/

Default Template

<div ng-controller="MyCtrl">
    <my-test my-test-url="myAjaxProperty"></my-test>
</div>

App Definition

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

myApp.directive('myTest', function(){
      return {
        restrict: 'E',
        repalce: 'true',
        template: '<div ng-show="myTestUrl">{{myTestUrl}}</div>',
          scope: { myTestUrl: '=' },
        link: function(scope, elem, attrs){

          scope.$watch('myTestUrl', function(newVal, oldVal){
            if(newVal){
              console.log("Watched value is defined as: "+scope.myTestUrl);
            }
          })
        }
      }
    });

function MyCtrl($scope, $timeout) {

    $timeout(function(){
        $scope.myAjaxProperty = "My Test Url";
        console.log("Ajax returned");
    }, 3000, true)


     console.log("Default Controller Initialized");
}

Другие советы

as long as you don't isolate your scope with,

scope: {}

in your directive, your scope has access to its parent controller's scope directly.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top