如何在具有隔离范围的指令中绑定到父作用域中的event.time变量而不在指令中使用$ parent?

时间:2018-04-24 14:35:40

标签: angularjs isolate-scope



angular.module('hfp.calendar')
    .controller('printPreviewCntrl', ['$scope', 'htmlFromServer',
    	function($scope, htmlFromServer){

    	    $scope.htmlReceived = htmlFromServer;
            $scope.event = {};

}])
.directive('compile', function($compile, $timeout) {

    return {
	    restrict: 'A',
		link: function(scope, element, attrs) {
			$timeout(function() {
				element.html(scope.$eval(attrs.compile));
				$compile(element.contents())(scope);
			});
		}
	};

})
.directive('initModel', function($compile) {

	return {
		restrict: 'A',
		scope: {
			eventField: '=initModel'
		},
		link: function(scope, element, attrs) {
			scope.eventField = element[0].innerText;
			element.attr('ng-bind', '$parent.' + attrs.initModel); // why do i have to use $parent here to make it work ?
			element.removeAttr('init-model');
			$compile(element)(scope);
		}
	};

});

<!-- clientside html -->
<input type="text" ng-model="event.time">
<div compile="htmlReceived">

</div>

<!-- html coming from server -->
<div init-model="event.time">
	10:30 AM
</div>
&#13;
&#13;
&#13;

我想从 initModel 指令绑定到父作用域var event.time,但它仅在我使用$ parent引用父作用域中的var时才有效。我可以在不使用$ parent的情况下实现此绑定吗?

1 个答案:

答案 0 :(得分:0)

无需使用隔离范围实现该指令。只需使用$parse服务:

&#13;
&#13;
angular.module("app",[])
.directive('initModel', function($parse) {
    return {
        restrict: 'A',
        //scope: {
        //	eventField: '=initModel'
        //},
        link: function(scope, elem, attrs) {
            var setter = $parse(attrs.initModel).assign;
            setter(scope, elem.text().trim());
            scope.$watch(attrs.initModel, function(value) {
                elem.text(value);
            });
        }        
     };
})
&#13;
<script src="//unpkg.com/angular/angular.js"></script>

<body ng-app="app" ng-init="event={}">
    <input type="text" ng-model="event.time">
    <div init-model="event.time">
	       10:30 AM
    </div>
</body>
&#13;
&#13;
&#13;

有关详细信息,请参阅AngularJS $parse Service API Reference