0

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>

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

4

1 回答 1

0

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

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);
            });
        }        
     };
})
<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>

有关更多信息,请参阅AngularJS $parse 服务 API 参考

于 2018-04-24T18:21:13.930 回答