如何将数据从控制器传递到自定义指令

时间:2016-10-06 15:53:36

标签: angularjs angularjs-directive custom-controls directive

我正在AngularJS中创建一个自定义指令。该指令应该打开一个弹出窗口来显示数据。弹出窗口的代码位于另一个html页面中,自定义指令将代码注入我的主页面。我可以打开弹出窗口但是我无法在弹出窗口中的任何位置显示现有数据。

通常情况下,我能够在主页面中显示数据,但数据不想进入自定义指令注入的html。

像这样我没有收到任何错误,但它没有传递数据。

注意:我必须修改一些代码以简化它。

这是我的自定义指令:

function updateCandidatePopup() {
   var directive = {}; 
   directive.restrict = "E";
   directive.scope = {}; 
   directive.templateUrl = "UpdateCandidatePopup.html";
   directive.controller = function ($scope) {
       $scope.SingleCandidate;
   }
   return directive;
}

这是我注册的地方:

myApp.directive("updateCandidatePopup", UpdateCandidatePopup);

这就是我在主页

中使用该指令的方法
<update-candidate-popup value="SingleCandidate" class="modal fade" ng-model="SingleCandidate" 
                        id="myUpdateModal" 
                        role="dialog" 
                        popup-data="SingleCandidate"> 
zxc</update-candidate-popup>

这是UpdateCandidatePopup.html:

<div> {{SingleCandidate.FirstName}} </div>

这是在弹出控制器中显示数据:(仅供参考,它仍然被修剪)

 myApp.controller('CandidatesController', function ($scope, $http, EmployerService, CandidateService) { //we injected localservice
    //Select single data for update
    $scope.getSingleData = function (C_ID) {
        alert(C_ID);
        $http.get('http://localhost:49921/api/Candidates/?C_ID=' + C_ID).success(function (data) {
            $scope.SingleCandidate = data; 
            $scope.FName = $scope.SingleCandidate.FirstName;
            alert($scope.SingleCandidate.FirstName);
            alert($scope.FName);
        }).error(function () {
            $scope.error = "An Error has occured while loading posts!";
        });
    };

});

2 个答案:

答案 0 :(得分:0)

抱歉错误!,回答了你的问题,我离开了,我发现了一个代码,可以解决你的问题。在你要采用的模板的后台,你让一个控制器和你的政策声明,让你去做那些值,我认为在你的情况下只是打印。

myApp.directive('editkeyvalue', function() {
return {
    restrict: 'E',
    replace: true,
    scope: {
        key: '=',
        value: '=',
        accept: "&"
    },
    template : '<div><label class="control-label">{{key}}</label>' +
    '<label class="control-label">{{key}}</label>' +
      '<input type="text" ng-model="value" />'+
    '<button type="button" x-ng-click="cancel()">CANCEL</button>' +
    '<button type="submit" x-ng-click="save()">SAVE</button></div>',

  controller: function($scope, $element, $attrs, $location) {        
    $scope.save= function() {
      console.log('from directive', $scope.key, $scope.value);    
      $scope.accept()
    };
  }
}
});

jsFiddle

答案 1 :(得分:0)

解决了下面的问题。它只是在指令控制器中注入$ scope。

myApp.directive("updateCandidatePopup", function () {
    return {
        templateUrl : "UpdateCandidatePopup.html",
        restrict: 'E',
        controller: function ($scope) {
        }
    }
});