0

I have a simple ASP.NET MVC application which contains a ng-controller. Using a partial view I inject inside this controller another ng-controller used only when needed. How can I make it work because I could not make the binding properly. Here's a plunker with a simplified version of what I need.

<body ng-app="MyApp">
  <div id='parent' ng-controller="MyCtrl">
    <label>Primitive</label>
    <input type="text" ng-model="name">

    <label>Object</label>
    <input type="text" ng-model="user.name">

    <button onclick="addNested();">Add Nested Controller</button>
  </div>
</body>

And the javascript part:

var app = angular.module("MyApp", []);

app.controller("MyCtrl", function($scope) {
  $scope.name = "ParentName";
  $scope.user = {
    name: "Peter"
  };
});

function addNested() {
    $('#parent').append(
        '<div class="nested" ng-controller="MyNestedCtrl">'+
              '<label>Primitive</label>' +
              '<input type="text" ng-model="name"><br />' +

              '<label>Primitive with explicit $parent reference</label> <br />' +
              '<input type="text" ng-model="$parent.name">' +

              '<label>Object</label>' +
              '<input type="text" ng-model="user.name">' +
          '</div>' +
          '<script type="text/javascript">' +
              'var a = angular.module("MyApp");' +
                'a.controller("MyNestedCtrl", ["$scope", MyNestedCtrl] );' +
          '</script>');
}

function MyNestedCtrl($scope) 
{
    $scope.name = "ChildName";
  $scope.user = {
    name: "Paul"
  };
}

2 Answers 2

1

If you want to manually insert bits of HTML, you must notify Angular that you have done so. Specifically, use the $compile service to link an HTML template with a specific scope, thereby making the bindings "live". It's preferable to do this sort of thing in a directive and not a controller, but for the purposes of demonstration, this will do.

Plunker: http://plnkr.co/edit/RmYYynlHKEoQWVbELYDP?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

you are writing jquery, not angularJS. In angular you should have an ng-view on the HTML, and in your code you should call a route (with ng-router) or a state (with ui-router) to replace the tempalte. Your HTML code can be in one of 2 places:

1) in your state definition under tempalte:
2) in an external HTML template file that will be referenced with the templateUrl: attribute.

the template will replace anything in your tag that has the ng-view attribute. So if you want to hide your button it should be:

   <div ng-view>
       <button> button goes here </button>
    </div>  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.